【问题标题】:Accessing nodejs functions inside expressJs static HTML在 expressJs 静态 HTML 中访问 nodejs 函数
【发布时间】:2013-02-18 04:13:14
【问题描述】:

我是 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() ?有什么好的方法来组织这样的文件?

【问题讨论】:

    标签: javascript node.js express


    【解决方案1】:

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

    【讨论】:

      【解决方案2】:

      代码如下所示

      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/

      【讨论】:

      • 嗯,我希望有更多的 PHP,比如我可以在 HTML 文档中引用一些服务器端 Javascript 内联。 Jade 工作正常,但是必须将我想要使用的所有参数传递给模板是很痛苦的。
      猜你喜欢
      • 2015-04-06
      • 1970-01-01
      • 1970-01-01
      • 2011-08-06
      • 2011-09-30
      • 1970-01-01
      • 1970-01-01
      • 2013-05-01
      • 1970-01-01
      相关资源
      最近更新 更多