您好,我正在研究Ethan Brown的“使用Node and Express的Web开发”。 在使用Handlebars Templates的书中,我找到了以下代码:
app.engine('handlebars', expressHandlebars({
defaultLayout: 'main',
helpers: {
section: function(name, options) {
if(!this._sections) this._sections = {}
this._sections[name] = options.fn(this)
},
}
}));
main.handlebars:
<!doctype html>
<html>
<head>
{{{_sections.title}}}
<link rel="stylesheet" href="css/main.css">
</head>
<body>
<header>
<img id= "header-logo" src="/img/logo.jpg">
</header>
{{{body}}}
</body>
</html>
view.handlebars:
{{#section 'title'}}
<title>Lore Ipsmum</title>
{{/section}}
<h1>Lore Ipsum</h1>
<p>Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor</p>
对此我有两个问题:
this
作为嵌入上下文被调用,因此可用于利用 view.handlebars 中{{#section 'title'}}
-Block的内容来呈现布局 main.handlebars 的上下文。我还是不太明白为什么
options.fn(this)
会以字符串形式返回{{#section 'title'}}
中的文字。