javascript - 将 mustache.js 部分与 express 结合使用

标签 javascript templates node.js express mustache

所以这可能是我完全误解功能的一个例子,但我正在尝试在 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/

相关文章:

Javascript 向上取整值

windows - 是否有任何环境变量代表 "C:\Documents and Settings"文件夹或 C :\Users folder in Windows?

javascript - 在 React Native 项目中使用 jest 进行单元测试 ("Not a function"错误)

javascript - 执行配置文件 app.json/process.yml 时找不到 Pm2 脚本

node.js - 如何隐藏nodemailer用于推送公共(public)github存储库的gmail密码?

javascript - node.js 异步 waterfall 调用以前的方法

c++ - 模板 <class = void*>,希望得到解释

templates - 如果 ArrayController 不包含 Ember 中的模型,则使用 bindAttr 禁用按钮

c++ - 基于策略的模板设计 : How to access certain policies of the class?

ruby - 当失败时自动从 node.js 中重新生成 ruby​​ 脚本