[英]Passing a variable to Handlebars when rendering a template
Is there a way to pass a variable to a handlebars template when it's rendering? 有一种方法可以在渲染时将变量传递给车把模板? I have this template:
我有这个模板:
<script id="listingTopics" type="text/x-handlebars-template">
{{#each this}}
<div class="wrapper_individual_listing_topic wrapper_form_dark">
<div class=" form_section">
<div class="topics_titles wrapper_listing_topics">
<a href="topic-{{id}}" class="listing-topics">{{title}}</a> <svg class="affinity {{heartClass}}" data-topicid="{{id}}"><use xlink:href="#starEmpty"/></svg>
</div>
<div class="topic-description hide topic-{{id}}">
<p class="text_standard">{{body}}</p>
</div>
</div>
</div>
{{/each}}</script>
And the variable I want to set when I render the template is heartclass 我渲染模板时要设置的变量是heartclass
My initial idea to do this was to set up a function: 我最初的想法是建立一个函数:
function showTopics(container, data, heartclass) {
var heartClass = heartclass
var listingTopicsCompiled = listingTopicsTemplate(data);
$(container).append(listingTopicsCompiled);
}
and then call the function like this 然后像这样调用函数
showTopics('#listing-topics', not_favorite_exchanges, 'unfav');
Not sure how to attack this. 不确定如何进行攻击。 Any help is very much appreciated!
很感谢任何形式的帮助!
I ended up just adding a foreach loop and adding the key value pair to each object in the array. 我最终只是添加了一个foreach循环,并将键值对添加到了数组中的每个对象。 So now it is this:
所以现在是这样的:
function showTopics(container, data, heartclass) {
data.forEach(function(entry) {
entry.heartClass = heartclass;
});
var heartClass = heartclass
var listingTopicsCompiled = listingTopicsTemplate(data);
$(container).html(listingTopicsCompiled);
}
However, I think it would be faster/better to somehow access a static variable. 但是,我认为以某种方式访问静态变量会更快/更好。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.