2017-01-23 46 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

相關問題