Handlebars模板中的多个部分

时间:2014-07-24 12:55:55

标签: handlebars.js

我只是更了解Handlebars作为模板解决方案并且遇到了一个我不知道如何解决的问题。 我已经在我的布局中添加了一些部分,一个用于标题,另一个用于页脚,用于从我的视图中动态插入脚本。但是,只有第一部分呈现。第二个(无论顺序如何)总是被省略。

我的布局是一个简单的HTML页面:

<!doctype html>
<html>
<head>
    <title>Test site</title>
    {{{_sections.head}}}
</head>
<body>
    <header>
        //Logo and stuff here
    </header>
    {{{body}}}




    <script src="//code.jquery.com/jquery-2.0.2.min.js"></script>
    {{{_sections.footer}}}
</body>
</html>

在我的布局文件中,我有:

{{#section 'head'}}
<script src="//cdnjs.cloudflare.com/ajax/libs/handlebars.js/1.3.0/handlebars.min.js"></script>
{{/section}}

//basic HTML here

{{#section ‘footer’}}
<script>
alert(“this doesn’t fire if its second!”);
</script>
{{/section}}

标题部分显示在页面上,但页脚没有。问题是,如果我将页脚放在页面的顶部(即{{section'head'}}之前,然后呈现但是头部不再呈现。

在我的app.js中,我按如下方式设置了部分功能:

var handlebars = require('express3-handlebars')
    .create({
        defaultLayout: 'main',
        helpers: {
            section: function (name, options) {
                if (!this._sections) {
                    this._sections = {};
                    this._sections[name] = options.fn(this);
                    return null;
                }
            }
        }
    });
app.engine('handlebars', handlebars.engine);
app.set('view engine', 'handlebars');

任何想法我在这里做错了什么或如何添加对这两个部分的支持?

由于

1 个答案:

答案 0 :(得分:5)

我认为你的部分会相互覆盖。尝试将把手更改为以下内容:

var handlebars = require('express3-handlebars')
    .create({
        defaultLayout: 'main',
        helpers: {
            section: function (name, options) {
                if (!this._sections) {
                    this._sections = {};
                }
                this._sections[name] = options.fn(this);
                return null;
            }
        }
    });
相关问题