From:http://www.oschina.net/question/12_21806
为了让 Node.js 输出更多的 HTML 元素,我们可以借助一些 html 模板引擎,例如 Mustache。
首先在 Node.js 中安装 Mustache:
npm install mustache
这会创建一个目录:node_modules\mustache
然后我们可以编写代码:
var mustache = require('./node_modules/mustache/mustache'); function helloworld(response) { console.log('request recieved at ' + (new Date()).getTime()); response.writeHead(200, {'Content-Type': 'text/html'}); var template = '<h1>Test</h1><p></p>'; var model = {helloworld:'Hello World'}; response.end(mustache.to_html(template,model)); } exports.helloworld = helloworld;
这段代码使用 to_html 函数生成网页,来看看执行效果:
但这看起来很不爽,我们希望模板独立于控制器之外,例如下面的模板:
<html> <head> <title>My first template</title> </head> <body> <h1>Test</h1> <p></p> </body> </html>
文件名是 helloworld.html.
为了使用这个模板文件,我们可以这样编写代码:
var mustache = require('./node_modules/mustache/mustache'); var fs = require('fs'); function helloworld(response) { console.log('request recieved at ' + (new Date()).getTime()); fs.readFile("./helloworld.html",function(err,template) { response.writeHead(200, {'Content-Type': 'text/html'}) response.write(mustache.to_html(template.toString(), {helloworld:"Hello World"})) response.end() }); } exports.helloworld = helloworld;
运行结果如下:
怎样,简单很多吧?:)