车把静态变量

Handlebars static variables

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

我正在为我的后端使用 express-handlebars,这是可能的。对于某些特定的渲染,我在前端使用 HandlebarsJS,但我找不到实现此目的的方法。

我想做的是

handlebars.static = {foo: 'bar'}

而不是将它添加到每个渲染器

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

要是能预编译到每个模板就好了

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

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>