在手柄中的助手内渲染模板 [英] Rendering templates within helpers in handlebars

查看:139
本文介绍了在手柄中的助手内渲染模板的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

通过句柄部分传递变量然而,我目前正在研究一个小小的解决方法来完成这项工作。所以,这个想法是注册一个辅助函数,它可以呈现一个具有可能值的特定模板。一些代码使得它更好理解。

Because there seem to be no answer on this: Passing variables through handlebars partial yet, I'm currently working on a little workaround to get this work. So, the idea is to register a helper function which renders a specific template with possible values. A bit code makes it better to understand.

这是我如何调用我的帮手:

This is how a I'd invoke my helper:

<div>
    {{myHelper}}
</div>

这个帮手注册了这个小代码:

This helper is registered with this little code:

hbs.registerHelper(name, function (args) {
    args = args || {};
    var template = hbs.compile(fs.readFileSync(__dirname + '/' + file, 'utf8'));
    return template(args);
});

我把这个snippiet放到一个循环中,一次注册不同的帮助者。这意味着'名称'和'文件'给出。

I put this snippiet into a loop to register different helpers at once. This means 'name' and 'file' is given.

好吧,现在我可以做这样的事情:

Okay now I'm able to do something like this:

// 'values' could be something like this:

var values = { headline: 'HEADLINE' }

<div>
    {{myHelper values}}
</div>

在助手中,我现在可以测试是否给定了某个值:

Within a helper I can now test if a certain values is given:

// myHelper template

<div>
    {{#if headline}}
    <h1>{{headline}}</h1>
    {{/if}}
    <p>Lorem ipsum</p>
</div>

这个小解决方法适用于我,但有一个问题。如上所述注册助手,返回一个简单的HTML转义字符串。因此,调用助手不会输出呈现的HTML片段。它将HTML输出为一个转义字符串。

This little workaround works for me, but there is one problem. Registering a helper as explained above, returns a plain HTML escaped string. So, invocing a helper doesn't output a rendered HTML snippet. It outputs the HTML as an escaped string.

您是否有任何想法让我的代码片段将HTML作为HTML返回?

Does anybody of you have an idea how I can make my code snippet return the HTML as HTML?

/ Pascal

/Pascal

推荐答案

From Handlebars doc

From Handlebars doc :


把手不会逃脱Handlebars.SafeString。如果你编写一个帮助程序来生成自己的HTML,你通常会
想要返回一个新的Handlebars.SafeString(结果)。在这种
的情况下,您将需要手动转义参数。

Handlebars will not escape a Handlebars.SafeString. If you write a helper that generates its own HTML, you will usually want to return a new Handlebars.SafeString(result). In such a circumstance, you will want to manually escape parameters.

尝试

Try

hbs.registerHelper(name, function (args) {
    args = args || {};
    var template = hbs.compile(fs.readFileSync(__dirname + '/' + file, 'utf8'));

    // return new hbs.SafeString(template(args));
    // From @Maroshii 
    // the SafeString method must be accessed through hbs.handlebars 
    // and not directly through hbs
    // https://github.com/donpark/hbs#handlebars

    return new hbs.handlebars.SafeString(template(args));
});

这篇关于在手柄中的助手内渲染模板的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆