在expressJs静态HTML中访问nodejs函数

时间:2012-04-18 20:37:27

标签: javascript node.js express

我是一个Javascript和Nodejs newb,我不知道如何最好地组织事情。我正在编写一个C ++应用程序的Web界面,使用Nodejs和V8转换来包装C ++ API。我的问题是,是否有某种方法可以使用Express来提供对nodejs中的函数/全局内容的引用?或者,为了做到这一点,我是否必须在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()?为这样的事情组织文件的好方法是什么?

2 个答案:

答案 0 :(得分:1)

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

答案 1 :(得分: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/

相关问题