带Express的把手:不同页面的不同html头

use*_*012 28 express handlebars.js

我在Express Node.js应用程序中使用Handlebars.我的layout.html文件包含一个<head>部分.如何使<head>不同页面的部分不同?(例如,我可以在一个页面中引用一个JavaScript文件,并<title>为每个页面改变.)

layout.html看起来像这样:

<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8">
    <script src='/public/ajsfile.js'></script>
    <link type='text/css' href="/public/style.css" rel="stylesheet">
  </head>
  <body>
    {{{body}}}
  </body>
</html>
Run Code Online (Sandbox Code Playgroud)

(我想象的是<head>用类似于{{{body}}}上面的东西改变内容,但是{{{head}}}.)

Eth*_*own 52

这是一个很好的问题,在我看来,Express的视图模型中存在一个明显的缺点.幸运的是,有一个解决方案:使用Handlebars 阻止助手.这是我用于此目的的助手:

helpers: {
    section: function(name, options){
        if(!this._sections) this._sections = {};
        this._sections[name] = options.fn(this);
        return null;
    }
}
Run Code Online (Sandbox Code Playgroud)

然后,在您的布局中,您可以执行以下操作:

<head>
    {{{_sections.head}}}
</head>
<body>
    {{{body}}}
</body>
Run Code Online (Sandbox Code Playgroud)

在你看来:

{{#section 'head'}}
    <!-- stuff that goes in head...example: -->
    <meta name="robots" content="noindex">
{{/section}}

<h1>Body Blah Blah</h1>
<p>This goes in page body.</p>
Run Code Online (Sandbox Code Playgroud)

  • 是的,Don:只需修改助手即可附加到_sections [name]而不是分配给.sections (2认同)

Fab*_*cio 7

您可以进行以下操作:

layout.hbs

<head>
    <title>{{title}}</title>
    {{#each css}}
        <link rel="stylesheet" href="/css/{{this}}" />
    {{/each}}
</head>
Run Code Online (Sandbox Code Playgroud)

app.js

router.get('/', function (req, res, next) {
    res.render('index', { title: 'MyApp', css: ['style.css', 'custom.css'] });
});
Run Code Online (Sandbox Code Playgroud)

结果:

<head>
    <title>MyApp</title>
    <link rel="stylesheet" href="/css/style.css" />
    <link rel="stylesheet" href="/css/custom.css" />
</head>
Run Code Online (Sandbox Code Playgroud)