繁体   English   中英

在Handlebars.js中的多个模板中使用同一数据对象

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM