【问题标题】:Handlebars static variables车把静态变量
【发布时间】:2015-12-23 05:20:10
【问题描述】:

是否可以为车把模板注册静态变量?

我在后端使用 express-handlebars,这是可能的。对于一些特定的渲染,我在前端使用 HandlebarsJS,但我无法找到实现这一点的方法。

我想要做的是类似的事情

handlebars.static = {foo: 'bar'}

而不是将其添加到每个渲染中

template({....., static: {foo:'bar'}});

如果我可以将它预编译到每个模板中就可以了。

【问题讨论】:

    标签: handlebars.js


    【解决方案1】:

    定义一个可以访问静态值的助手。这是一个例子:

    var templates = Handlebars.templates = Handlebars.templates || {};
    
    /**
     * Reads property from object. Supports reading nested properties with dot or bracket notation.
     */
    var readProperty = function(object, property) {
      var value = object;
      property = property.replace(/\[('|")?|('|")?\]/g, '.');
      if (property.substring(property.length - 1) === '.') {
          property = property.slice(0, property.length - 1);
      }
      property.split('.').forEach(function(name) {
        value = value[name];
      });
      return value;
    };
    
    /**
     * The object that holds the values available to all the templates. This must be accessible by the helper definition.
     */
    var values = {
      key: 'a value',
      lists: {
        numbers: [0,1,2,3,5], 
      },  
    };
    
    Handlebars.registerHelper('values', function(property) {
      return readProperty(values, property);
    });
    
    templates['template-a'] = Handlebars.compile($('#template-a').html());
    templates['template-b'] = Handlebars.compile($('#template-b').html());
    
    $('body').append(templates['template-a']());
    $('body').append(templates['template-b']());
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <script src="http://builds.handlebarsjs.com.s3.amazonaws.com/handlebars-v4.0.5.js"></script>
    <script id="template-a" type="text/x-handlebars-template">
      <p>here's the value: <strong>{{values 'key'}}<strong></p>
    </script>
    <script id="template-b" type="text/x-handlebars-template">
      <p>again: <strong>{{values 'key'}}</strong><br>
      and another one from an array inside an object: <strong>{{values 'lists.numbers[3]'}}</strong><br>
      using bracket notation: <strong>{{values 'lists["numbers"]'}}</strong></p>
    </script>

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-07-20
      • 1970-01-01
      • 2015-08-26
      • 2016-02-16
      • 2012-07-16
      • 2017-12-27
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多