TL;博士
在下面的车把模板中。
<div class="field field-label">
<label>{{label}}</label><input type="text" value="{{{{attribute}}}}">
</div>需要计算{{属性}},但要打印属性}}"的}}"值。
背景
我对模板有个有趣的用途。我的应用程序有几十个表单(并且正在增长!),以及几种显示它们的方法。显然,它们可以显示在浏览器,或移动设备,或PDF等.因此,我想要做的是在JSON中定义这些表单,以适应像MongoDB这样的地方。这样,它们就可以很容易地被修改,而不需要HTML视图、移动应用程序和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。在嵌套的可选表单中,它变得相当复杂,但您明白了问题所在。
问题是,现在我有了和两个上下文。第一个是带有表单数据的JSON,第二个是来自模型的JSON。我有两个选择我认为会很好。
解决方案1
包含注册为助手的模型上下文的快速小闭包。
var fn = (function(model) {
return function(attr) {
return model[attr]
}
})(model);
Handlebars.registerHelper('model', fn)...to是这样使用的.
<input type="text" name="{{name}}" value="{{model attribute}}">解决方案2
两次传球。让我的模板输出一个模板,然后我可以编译和运行我的模型。我有一个很大的优势,我可以预编译表格。我更喜欢这种方法。这是我的问题。如何从模板中打印{{属性}?
例如,在我的文本模板中..。
<div class="field field-label">
<label>{{label}}</label><input type="text" value="{{{{attribute}}}}">
</div>我需要评估{{attribute}}并打印{{属性值}}。
发布于 2013-08-29 19:51:41
我用了解决方案2,有点。对我来说,预编译表单sans数据是很重要的。所以我只是添加了一些辅助函数..。
Handlebars.registerHelper('FormAttribute', function(attribute) {
return new Handlebars.SafeString('{{'+attribute+'}}');
});
Handlebars.registerHelper('FormChecked', function(attribute) {
return new Handlebars.SafeString('{{#if ' + attribute + '}}checked="checked"{{/if}}');
});我可以在表单模板中使用...that .
<input type="text" name="{{name}}" value="{{FormAttribute attribute}}">...that导致.
<input type="text" name="FirstName" value="{{FirstName}}">我仍然有兴趣了解是否有一些方法可以让把手忽略而不解析花括号{{}}而不使用帮助器。
https://stackoverflow.com/questions/18495007
复制相似问题