了解车把辅助功能:options.fn()

时间:2020-02-21 16:55:45

标签: javascript node.js express handlebars.js

您好,我正在研究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>

对此我有两个问题:

  1. 据我了解,辅助函数以this作为嵌入上下文被调用,因此可用于利用 view.handlebars {{#section 'title'}}-Block的内容来呈现布局 main.handlebars 的上下文。我还是不太明白为什么 options.fn(this)会以字符串形式返回{{#section 'title'}}中的文字。
  2. 这显然是一种骇人听闻的解决方案;考虑到能够在一个视图中声明不必在生成的呈现页面上连贯显示的多个内容是多么有用和方便,我认为有充分的理由说明为什么没有一种更简单的方法可以/为什么不是默认功能?

0 个答案:

没有答案
相关问题