assemble - Render a list of strings as Handlebars

2019-07-11 00:17发布

Using the assemble i actually stuck on a problem which i can't fix myself.

I'm defining a bunch of widgets in the YAML front matter section and including an partial aside {{> aside}}. Until here everything works as expected!

What i'm trying to do now, is to take the list widgets and rendering my partials within the aside template. But anyhow it does not work as expected.

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}}

Using {{.}} prints my above defined list as string. But if i try to do {{> .}} this, the console drops the following warning:

Warning: The partial . could not be found Use --force to continue.

1条回答
小情绪 Triste *
2楼-- · 2019-07-11 00:20

I found a way by creating a custom helper that can be invoked from any Handlebars template. Now i'm able to use {{renderPartial 'partialName' context}}.

In my template:

var aside = ['my-widget-a','my-widget-b','my-widget-x'];

{{#each aside}}
    {{renderPartial this ../this}}
{{/each}}

Javascript Module

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);
    });
};
查看更多
登录 后发表回答