【问题标题】:assemble - Render a list of strings as Handlebars partialassemble - 将字符串列表渲染为 Handlebars 部分
【发布时间】:2014-01-28 10:51:46
【问题描述】:

使用assemble 我实际上遇到了一个我自己无法解决的问题。

我在YAML front matter 部分中定义了一堆widgets,并包括部分{{> aside}}。直到这里一切都按预期工作!

我现在要做的是获取列表小部件并在备用模板中呈现我的部分。但无论如何它并没有按预期工作。

src/templates/layouts/layout-default.hbs

---
layout: src/templates/layouts/layout-default.hbs
widgets:
    - widget_link-list
    - widget_welcome-message
---

<section role="main">
    <h1>Template TwoCol</h1>
    {{> body }}
</section>
<aside role="complementary">
    {{> aside}}
</aside>

src/templates/partials/aside.hbs

{{#each widgets}}
    {{.}}
{{/each}}

使用{{.}} 将我上面定义的列表打印为字符串。但如果我尝试这样做{{&gt; .}},控制台会丢弃以下警告:

警告:部分 .找不到使用 --force 继续。

【问题讨论】:

    标签: gruntjs assemble


    【解决方案1】:

    我通过创建可以从任何 Handlebars 模板调用的自定义帮助程序找到了一种方法。现在我可以使用{{renderPartial 'partialName' context}}

    在我的模板中:

    var aside = ['my-widget-a','my-widget-b','my-widget-x'];
    
    {{#each aside}}
        {{renderPartial this ../this}}
    {{/each}}
    

    Javascript 模块

    module.exports.register = function (Handlebars, context) {
    
        Handlebars.registerHelper("renderPartial", function (name) {
    
            var fn,
                template = Handlebars.partials[name];
    
            if (typeof template !== 'Function') {
                // not compiled, so we can compile it safely
                fn = Handlebars.compile(template);
            } else {
    
                // already compiled, just reuse it
                fn = template;
            }
    
            var output = fn(context).replace(/^\s+/, '');
    
            return new Handlebars.SafeString(output);
        });
    };
    

    【讨论】:

    猜你喜欢
    • 2014-01-10
    • 1970-01-01
    • 1970-01-01
    • 2015-11-01
    • 2013-10-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-26
    相关资源
    最近更新 更多