Handlebars with Express:不同的html头为不同的页面

前端之家收集整理的这篇文章主要介绍了Handlebars with Express:不同的html头为不同的页面前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我在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>

(我想象的是,使用类似于{{{body}}}的{< head>内容,而在{{{head}}}中)

解决方法

这是一个很好的问题,在我看来,Express的观点模式是一个明显的弱点。幸运的是,有一个解决方案:使用Handlebars块助手。这是我为此目的使用的帮手:
helpers: {
    section: function(name,options){
        if(!this._sections) this._sections = {};
        this._sections[name] = options.fn(this);
        return null;
    }
}

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

<head>
    {{{_sections.head}}}
</head>
<body>
    {{{body}}}
</body>

在你看来:

{{#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>
原文链接:https://www.f2er.com/html/232594.html

猜你在找的HTML相关文章