【发布时间】:2012-07-06 21:30:42
【问题描述】:
所以这可能是我完全误解了功能的情况,但我试图在 node.js 中使用部分,以便在我的各种模板上有一个可重用、可重新插入的页眉和页脚,类似于 django 或 @ 中的 {% extends 'something.html' %} 987654324@ 在 php 中。据我了解,这就是部分的用途。
所以在我的 app.js 中使用这个配置来渲染模板:
var mustache = require('mustache');
var template = {
compile: function (source, options) {
if (typeof source == 'string') {
return function(options) {
options.locals = options.locals || {};
options.partials = options.partials || {};
if (options.body) // for express.js > v1.0
locals.body = options.body;
return mustache.to_html(
source, options.locals, options.partials);
};
}
else {
return source;
}
},
render: function (template, options) {
template = this.compile(template, options);
return template(options);
}
};
// Configuration
app.configure(function(){
app.register(".html", template);
app.set('views', __dirname + '/views');
app.set('view options', {layout: false});
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(app.router);
app.use(express.static(__dirname + '/public'));
});
然后我有这条路线:
var header = require("../views/header.html");
module.exports = function(app){
app.all('/test', function(req, res){
var data = {
locals: {value: "some value"},
partials: {header: header}
}
res.render('test.html', data);
});
header.html 就是这样:
hello world
而 test.html 就是这样:
{{>header}}
{{ value }}
我希望这会呈现:
hello world
some value
但是当我在 header.html 中运行 node app.js 指向 hello world 作为问题时,我得到了一个意外的令牌错误。
我在配置它以使其正常工作时缺少什么?
【问题讨论】:
-
省去很多麻烦,使用 hulk-hogan (github.com/quangv/hulk-hogan)。它支持带有
{{{body}}}的布局文件。 -
是的,使用 hulk-hogan 在大约五秒钟内解决了我的问题。不过,我仍然有兴趣知道如何本地配置它。
-
正如项目页面指出的那样,没有真正好的解决方案。于是有了这个项目。
标签: javascript templates node.js express mustache