2017-01-23 52 views
0

我想在不同的上下文中跨多个模板使用相同的数据对象,我如何重用它。无论如何,在这种情况下,车把部分将有所帮助。在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”,如果有人有这个想法!

+0

您可以像使用第一个模板一样在另一个模板中使用它。 – 76484

+0

你可以分享这样的场景的任何例子@ 76484 – Learner

+0

你是谁希望重用该对象,所以大概你已经有一个场景。如果您发布了您尝试过的代码,那么我可以尝试帮助您。 – 76484

回答

2

为了获得第二个模板,您必须从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)); 

一个例子来看看这个fiddle

+0

非常感谢!得到了错误,这个小提示代码片段真的很有帮助。 – Learner

相关问题