Handlebars.js - 构建模板模板

时间:2013-08-28 17:57:46

标签: javascript handlebars.js

TL; DR

在以下Handlebars模板中......

<div class="field field-label">
  <label>{{label}}</label><input type="text" value="{{{{attribute}}}}">
</div>

我需要评估{{attribute}},但需要打印value="{{ 属性 }}"的值。

背景

我对模板有一个有趣的用途。我的应用程序有几十种形式(并且还在增长!),以及几种显示它们的方法。显然,它们可以显示在浏览器,移动设备或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 yada。嵌套的可选表单相当复杂,但你明白了。

问题是,现在我有两个上下文。第一个是带有表单数据的JSON,第二个是来自模型的JSON。我认为有两种选择可行。

解决方案1 ​​

包含注册为帮助程序的模型上下文的快速小闭包。

var fn = (function(model) {
  return function(attr) {
    return model[attr]
  }
})(model);

Handlebars.registerHelper('model', fn)

......像这样使用......

<input type="text" name="{{name}}" value="{{model attribute}}">

解决方案2

两次通过。让我的模板输出一个模板,然后我可以编译并运行我的模型。一个很大的优点,我可以预编译表单。我更喜欢这种方法。这是我的问题。 如何从模板中打印{{attribute}}?

例如,在我的文本模板中......

<div class="field field-label">
  <label>{{label}}</label><input type="text" value="{{{{attribute}}}}">
</div>

我需要对{{attribute}}进行评估并打印{{属性值}}。

1 个答案:

答案 0 :(得分:0)

我选择了解决方案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}}');
});

...我可以在我的表单模板中使用...

<input type="text" name="{{name}}" value="{{FormAttribute attribute}}">

......导致......

<input type="text" name="FirstName" value="{{FirstName}}">

我仍然有兴趣了解是否有某种方法可以忽略Handlebars而不使用帮助器解析大括号{{}}。