gpt4 book ai didi

express - 带有 Express : different html head for different pages 的 Handlebars

转载 作者:行者123 更新时间:2023-12-03 09:45:19 24 4
gpt4 key购买 nike

我在 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>

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

最佳答案

这是一个很好的问题,在我看来,这是 Express View 模型的一个明显弱点。幸运的是,有一个解决方案:使用 Handlebars block 助手。这是我为此目的使用的助手:

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>

关于express - 带有 Express : different html head for different pages 的 Handlebars ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21737057/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com