使用小胡子.js部分与快递

Using mustache.js partials with express

本文关键字:快递 js 小胡子      更新时间:2023-09-26

所以这可能是我完全误解功能的情况,但我正在尝试在节点中使用部分.js以便我在各种模板上有一个可重用的、可重新插入的页眉和页脚,类似于 django 中的{% extends 'something.html' %}或 php 中的<? includes 'something.php ?>。据我了解,这就是部分的用途。

所以在我的应用程序中.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);
});

标题.html就是这样:

hello world

和测试.html就是这样:

{{>header}}
{{ value }}

我希望这会呈现:

hello world
some value

但是当我运行node app.js指向标头中的hello world时,我收到意外的令牌错误.html这是问题所在。

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

对于部分以及如何使它们工作,我建议看看合并.js项目。将多个模板引擎与Express 3.x集成是一个难题

这个线程很旧,但也许像我这样留着胡子的初学者最终会像我一样在这里遇到同样的问题。

在我的情况下,问题是我省略了模板中的">"。

  • 快递:"^4.17.1"
  • 胡须快递:"^1.3.0"

在 myRouter.ts 中

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

在模板中.胡子

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

我希望这对其他人有所帮助