经过大量的努力,我在测试站点上实现了handlebarsjs,以便在用户输入数据时显示它们。
为了显示不同模板样式的用户输入,我不得不以相同的形式多次重复相同的handlebarsjs代码。
有没有一种方法可以将重复的车把代码放置在外部页面中,然后将该外部页面包括在重复的车把代码中?
我不确定语法,甚至不确定handlebarsjs是否可以使用这种方法(我已经尝试了几件事-但无法正常工作)。
这是我所选择的重复代码:
{{# if address_style_one_line }}
{{! address is to be displayed across one line - replaced line breaks with line space }}
{{# if address_style_01 }}
....
{{else}}
{{# if address_style_02 }}
....
{{else}}
{{! address is to be displayed across more than one line - use this format as the template for the address scross one line style }}
{{# if address_style_01 }}
....
{{else}}
{{# if address_style_02 }}
....
{{/if}}
最佳答案
您应该能够使用局部函数来完成此任务。局部变量允许您在其他模板中重用模板。
说明文件:
基本用法:http://handlebarsjs.com/#partials
其他功能:http://handlebarsjs.com/partials.html
粗略的例子:
<script id="address-template" type="text/x-handlebars-template">
{{# if address_style_one_line }}
{{> address}}
{{else}}
{{> address}}
{{/if}}
</script>
<script id="address-partial" type="text/x-handlebars-template">
// repeated template goes here
{{! address is to be displayed across one line - replaced line breaks with line space }}
{{# if address_style_01 }}
....
{{else}}
{{# if address_style_02 }}
....
</script>
<script type="text/javascript">
$(document).ready(function() {
// register partial
Handlebars.registerPartial("address", $("#address-partial").html());
});
</script>
关于javascript - handlebarsjs-如何使用include代替重复的代码,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/31898025/