【问题标题】:Using mustache.js partials with express将 mustache.js 部分与 express 一起使用
【发布时间】: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 作为问题时,我得到了一个意外的令牌错误。

我在配置它以使其正常工作时缺少什么?

【问题讨论】:

标签: javascript templates node.js express mustache


【解决方案1】:

对于部分以及如何使它们工作,我建议查看consolidate.js 项目。将多个模板引擎与 express 3.x 集成是一种努力

【讨论】:

  • 所以它基本上是把他们拿出来的东西放回 expressjs 中?在我看来,从 express 中删除对模板和部分的支持是一个错误。
  • 我喜欢框架不试图牵着我的手去做所有事情。没有人愿意被作者的观点所束缚。
  • 当然,把东西拿出来也是作者的一种自以为是的行为。现在我们必须找到其他解决方案来让我们的应用程序与新版本兼容。
  • 好吧,对于这个特殊的删除,让它成为模板引擎的责任是有意义的。我的理解是支持这么多引擎是一个皮塔饼。对于下一个版本, res.render 可能会被完全删除。
【解决方案2】:

这个帖子很老了,但也许像我这样留着小胡子的初学者会像我一样在这里遇到同样的问题。

就我而言,问题是我在模板中省略了“>”..

  • 表达:“^4.17.1”
  • mustache-express:“^1.3.0”

在 myRouter.ts 中

router.all('/', (req: Request, res: Response, next: NextFunction)  => {
  res.render('index', {
    pageTitle: 'Welcome',
    partial: res.render('partial',{...})
  });
});

在 template.mustache 中

<html>
  <head>
    <title>{{pageTitle}}</title>
  </head>
  <body>
    {{>partial}}
   </body>
</html>

我希望这对其他人有帮助

【讨论】:

    猜你喜欢
    • 2012-09-24
    • 1970-01-01
    • 1970-01-01
    • 2011-06-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-10-25
    相关资源
    最近更新 更多