所以这可能是我完全误解功能的一个例子,但我正在尝试在 node.js 中使用部分组件,以便在我的各种模板上有一个可重复使用、可重新插入的页眉和页脚,类似于 {% extends 'something.html' %}
在 django 或 <? includes 'something.php ?>
在 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
但是当我运行 node app.js
时出现意外的 token 错误指向 hello world
在我的 header.html 作为问题。
我在配置它时缺少什么才能让它工作?
最佳答案
对于部分以及如何使它们工作,我建议看一下 consolidate.js项目。将多个模板引擎与 express 3.x 集成是一个努力
关于javascript - 将 mustache.js 部分与 express 结合使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11369901/