0

我是 Javascript 和 Nodejs 新手,我不确定如何最好地组织事情。我正在通过使用 Nodejs 和 V8 转换来包装 C++ API 来为 C++ 应用程序编写 Web 界面。我的问题是,有没有什么方法可以使用 Express 来提供在 nodejs 中引用函数/全局的 HTML?或者我是否必须求助于在 HTML 中有一堆 res.write(html) 类型的调用才能做到这一点?

例如,我想用从 C++ 配置 API 访问的内容预填充表单数据。C++ API 封装在一个 Nodejs 模块中。现在任何需要动态生成的东西(比如预填充的表格)我只是做类似的事情,

var novaconfig = require('./NodeAppConfig/build/Release/appconfig');
var AppConfiguration = new Appconfig.AppConfigBinding();

var express=require('express');
var app = express.createServer(express_options);

app.configure(function () {
    app.use(express.methodOverride());
    app.use(express.bodyParser());
    app.use(app.router);
    });


app.get('/configureApplication.html', function(req, res) {
    console.log("[200] " + req.method + " to " + req.url);
    res.writeHead(200, "OK", {'Content-Type': 'text/html'});
    res.write('<HTML>');
    res.write('<HEAD>');
    res.write(' <link rel="stylesheet" type="text/css" href="configstyle.css" media="screen">');
    res.write('</HEAD>');
    res.write('<BODY>');

    res.write('<label>');
    res.write(Interface);
    res.write('</label>');
    res.write('<form method="post" action="/configureNovaSave">');
    res.write('<input type="text" name="interface" value="');
    res.write(AppConfiguration.GetCurrentInterface());
    res.write('" /><br />');

    res.write('<input type="submit" name="submitbutton" id="submitbutton" value="Save Settings" />');
    res.write('</form>');
    res.write("<br/>");
    res.write('</BODY>');
    res.write('</HTML>');

    res.end();
});

但这显然是一个不好的方法。有没有办法让动态生成的 HTML 在一个独立的文件中,然后仍然在其中访问 AppConfiguration.GetCurrentInterface() ?为这样的事情组织文件的好方法是什么?

4

2 回答 2

1

我认为您想要的是模板引擎。也许看看 Jade 或 Mustache。然后你只需传入你想要动态的部分,引擎就会为你呈现页面。

于 2012-04-18T20:39:58.660 回答
1

代码如下所示

app.get('/configureApplication.html', function(req, res) {
    var config = AppConfiguration.GetCurrentInterface();
    res.render('configureApplication.jade', {locals: {config: config}});
});

configureApplication.jade 可以访问变量“config”,如下所示

doctype 5
html(lang="en")
  head
    title= config

完整的文档在这里

http://jade-lang.com/

于 2012-04-18T21:00:06.540 回答