【发布时间】:2017-12-10 18:32:52
【问题描述】:
在 Handlebars 中,当没有提供上下文数据时,默认不呈现任何内容:
例如如果上下文中没有提供 title 变量,title: {{ title }} 将呈现 title:
我想构建一个助手,在提供上下文时正确评估模板,但在没有提供上下文变量时显示实际的胡子模板。
Here is a Plunk that illustrates this idea
我可以使用以下代码有条件地显示渲染或模板:
{{#unless title}}
{{{{raw-helper}}}}
<h2>title: {{title}}</h2>
{{{{/raw-helper}}}}
{{else}}
<h2>title: {{title}}</h2>
{{/unless}}
但我认为一个更优雅、更可重用的解决方案是创建一个特定的助手。我会这样使用它:
{{#raw-unless body}}
body: {{body}}
{{/raw-unless}}
如果body字符串不为空/null/未定义,它会渲染:
body: 'this is the body provided in context'
如果没有提供body,它会渲染:
body: {{body}}
到目前为止,我尝试像这样注册助手:
Handlebars.registerHelper('raw-unless', function(data, options) {
if(data) {
return options.fn(this);
}
else {
var out = '{{#raw-helper}}';//
out += options.fn();
out += '{{/raw-helper}}';//
return out;
}
});
但它呈现:{{#raw-helper}} body: {{/raw-helper}}
我不熟悉自定义助手创建,任何帮助表示赞赏
【问题讨论】:
标签: javascript handlebars.js templating