是否可以为手柄模板注册静态变量?
我在后端使用快速把手,这是可能的。对于某些特定的渲染,我在前端使用HandlebarsJS,我无法找到实现此目的的方法。
我想做的是像
handlebars.static = {foo: 'bar'}
而不是将其添加到每个渲染
template({....., static: {foo:'bar'}});
如果我可以将其预编译到每个模板中,那就没问题了。
答案 0 :(得分: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>
&#13;