TL;DR
在以下 Handlebars 模板中...
<div class="field field-label">
<label>{{label}}</label><input type="text" value="{{{{attribute}}}}">
</div>
我需要评估 {{attribute}} 但
value="{{
属性值 }}"
要打印。背景
我对模板有一个有趣的用途。我的应用程序有几十种形式(而且还在不断增加!),以及几种显示它们的方式。显然它们可以显示在浏览器、移动设备或 PDF 等中......所以我想做的是在 JSON 中定义这些表单,以便在 MongoDB 之类的地方存在。这样,无需更新 HTML View 、移动应用程序和 PDF 渲染功能即可轻松修改它们。
{
title: 'Name of this Form',
version: 2,
sections: [
{
title: 'Section Title',
fields: [
{
label: 'Person',
name: 'firstname',
attribute: 'FIRST',
type: 'text'
}, {
label: 'Birthday',
name: 'dob',
attribute: 'birthday',
type: 'select',
options: [
{ label: 'August' },
{ label: 'September' },
{ label: 'October' }
]
},
...
...
那是一种味道。所以
type: 'text'
结果 <input type="text">
, name
是输入的名称,attribute
是模型的属性,yada yada。嵌套的可选表单变得相当复杂,但你明白了。问题是,现在我得到了 两种情况 .第一个是带有表单数据的 JSON,第二个是来自模型的 JSON。我有两个我认为会很好的选择。
解决方案一
包含注册为助手的模型上下文的快速小闭包。
var fn = (function(model) {
return function(attr) {
return model[attr]
}
})(model);
Handlebars.registerHelper('model', fn)
......像这样使用......
<input type="text" name="{{name}}" value="{{model attribute}}">
解决方案二
两通。让我的模板输出一个模板,然后我可以用我的模型编译和运行该模板。一大优势,我可以预编译表格。我更喜欢这种方法。这是我的问题。 如何从我的模板中打印出 {{attribute}}?
例如,在我的文本模板中......
<div class="field field-label">
<label>{{label}}</label><input type="text" value="{{{{attribute}}}}">
</div>
我需要
{{attribute}}
要评估并打印 {{value of attribute}}。
最佳答案
我选择了解决方案2,有点。对我来说重要的是我可以预编译没有数据的表单。所以我所做的只是添加了一些辅助函数......
Handlebars.registerHelper('FormAttribute', function(attribute) {
return new Handlebars.SafeString('{{'+attribute+'}}');
});
Handlebars.registerHelper('FormChecked', function(attribute) {
return new Handlebars.SafeString('{{#if ' + attribute + '}}checked="checked"{{/if}}');
});
...我可以在我的表单模板中使用...
<input type="text" name="{{name}}" value="{{FormAttribute attribute}}">
……结果……
<input type="text" name="FirstName" value="{{FirstName}}">
我仍然有兴趣了解是否有某种方法可以让 Handlebars 在不使用帮助程序的情况下忽略并且不解析大括号 {{}}。
关于javascript - Handlebars.js - 构建模板模板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18495007/