【发布时间】:2016-07-01 15:26:29
【问题描述】:
这几天,我开始使用 Handlebars,目前正在尝试使用装饰器。当它保持简单时,我已经了解它是如何工作的: 例如:单独装饰名字:bill gaTes -> Mr Bill GATES
然后我尝试在“每个”循环中使用装饰器,以与以前完全相同,但使用人员列表而不是一个人。问题是:当我在装饰器函数中时,我需要知道我正在查看哪个元素(来自数组)。
所以我想在参数中给出“每个”循环的索引(然后,由于我可以访问数据,我可以检索当前元素)或当前元素。
我尝试使用@index(通常效果很好),但在调试时我得到未定义。 而且我找不到在我的装饰器中获取当前元素的方法。
代码如下:
index.html
<!doctype html>
<html>
<head>
<title>Test Handlebars Decorators 4</title>
</head>
<body>
<div id = "main"> </div>
<script id = "rawTemplate" type = "text/x-handlebars-template">
{{#each this}}
Decorated: {{formatGenderHelper this}}
{{* activateFormatter @index}}
<br />
{{/each}}
</script>
<script type = "text/javascript" src = "js/lib/handlebars.min-latest.js"></script>
<script type = "text/javascript" src = "js/lib/jquery-2.2.4.min.js"></script>
<script type = "text/javascript" src = "js/data.js"></script>
<script type = "text/javascript" src = "js/index.js"></script>
</body>
</html>
data.js
var data = [{
"firstname": "Bill",
"lastname": "Gates",
"gender": "MALE"
}, {
"firstname": "Hillary",
"lastname": "Clinton",
"gender": "FEMALE"
}];
function formatMale(author) {
return "M. " + author.firstname + " " + author.lastname.toUpperCase();
}
function formatFemale(author) {
return "Mme " + author.firstname + " " + author.lastname.toUpperCase();
}
Handlebars.registerDecorator('activateFormatter', function(program, props, container, context) {
var genderHelper;
var gender = context.args[0] || context.data.root[0].gender;
switch(gender) {
case "MALE":
genderHelper = formatMale;
break;
case "FEMALE":
genderHelper = formatFemale;
break;
default:
console.log('Gender format not set. Please set before rendering template.');
genderHelper = function() {};
}
container.helpers = {
formatGenderHelper: genderHelper
};
});
index.js
// Get the template
var rawTemplate = $('#rawTemplate').html();
// Compile the template
var compiledTemplate = Handlebars.compile(rawTemplate);
// Apply the template on the data
var content = compiledTemplate(data);
// Finally, re-inject the rendered HTML into the DOM
$('#main').html(content);
如果您需要更多信息,请告诉我。
感谢您的帮助:)
【问题讨论】:
-
我认为这不是装饰器的正确用法。我认为装饰器定义了整个块的格式化功能,而不是单个项目。
-
你能再详细解释一下你的意思吗?
-
@Barudar 装饰器与父块同时运行,而不是与装饰器所在的子块同时运行。通过这种方式,它在某种程度上打破了关于模板中块执行顺序的典型推理。实际上,对于上述情况,这意味着它运行一次以配置整个父
#each块的格式化功能,而不是为#each迭代项目创建的每个子块。 -
@Joshua Skrzypek 好的,谢谢您的解释。但是,我仍然不明白装饰器的目的是什么。我的意思是,看起来我们可以用装饰器做的所有事情也可以用助手来完成。所以装饰器肯定有一些特定的用途,它们确实比助手更好。
标签: javascript templates handlebars.js decorator