[英]Use the same data object across multiple templates in Handlebars.js
我想在不同上下文中的多個模板中使用同一數據對象,如何重用它。 在這種情況下,手把零件可能會有所幫助。
$("document").ready(function(){
var source = $("#homePage-template").html();
var template = Handlebars.compile(source);
var dataPanel = {activites:[
{activity: "Events" , activityRedirect:"#", icon:"fa fa-camera-retro" , imageUrl:"xyz"},
{activity: "Ciriculars" , activityRedirect:"#", icon:"fa fa-paper-plane", imageUrl:"xyz"}
]};
$("#homePage-placeholder").html(template(dataPanel));
$("#another-placeholder").html(template(dataPanel));
});
這是我的模板:
<script id="homePage-template" type="text/x-handlebars-template">
<ul>
{{#activites}}
<li><i class="{{icon}}" aria-hidden="true"></i><a href="{{activityRedirect}}">{{activity}}</a></li>
{{/activites}}
</ul>
</script>
另一個模板
<script id="another-template" type="text/x-handlebars-template">
{{#activites}}
<div>
<img src="{{imageUrl}}"/>
<span>{{activity}}</span>
</div>
{{/activites}}
</script>
現在,我該如何將這些數據重用到“另一個模板”中,因為我要在其中包含圖像和文本,但是如果有人對此有想法,它只能像列表形式呈現“ homePage-template”!
為了擁有第二個模板,您必須從DOM中獲取其HTML源代碼,並將其編譯為模板方法,就像對主頁模板所做的一樣。
var homepage_template_source = $('#homePage-template').html();
var another_template_source = $('#another-template').html();
var homepage_template = Handlebars.compile(homepage_template_source);
var another_template = Handlebars.compile(another_template_source);
您必須為要呈現的特定模板調用模板方法:
$("#homePage-placeholder").html(homepage_template(dataPanel));
$("#another-placeholder").html(another_template(dataPanel));
有關示例,請參見此小提琴 。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.