Handlebars.js-构建模板模板

Handlebars.js - Building a Template Template

本文关键字:建模 构建 js- Handlebars      更新时间:2023-09-26

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}},并打印{属性的{值}}。

我采用了解决方案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忽略并且在不使用助手的情况下不解析花括号{{}}。