问题描述
我在Express Node.js应用程序中使用Handlebars。我的layout.html文件包含一个< head>
部分。如何使不同页面的< head>
部分不同? (例如,我可以在一页中引用一个JavaScript文件,并为每个页面更改< title>
。)
I am using Handlebars in an Express Node.js app. My layout.html file includes a <head>
section. How can I make the <head>
section different for different pages? (So that I can, for example, reference a JavaScript file in only one page, and vary the <title>
for each page.)
layout.html看起来像这样:
layout.html looks like this:
<!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>
(我想象会变化< head>
内容与上述类似于 {{body}}}
的内容,但使用 {{{head}}}
。)
(I am imagining varying the <head>
content with something analogous to {{{body}}}
in the above, but with {{{head}}}
.)
推荐答案
这是一个很好的问题,在我看来,Express的视图模式是一个明显的弱点。幸运的是,有一个解决方案:使用Handlebars 块助手。这是我为此目的使用的帮助器:
This is a great question and, in my mind, a glaring weakness in Express's view model. Fortunately, there is a solution: use Handlebars block helpers. Here's the helper I use for this purpose:
helpers: {
section: function(name, options){
if(!this._sections) this._sections = {};
this._sections[name] = options.fn(this);
return null;
}
}
然后,在布局中,您可以执行以下操作:
Then, in your layout, you can do the following:
<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>
这篇关于Handlebars with Express:不同的html头为不同的页面的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!