我使用胡子js来渲染一个包含API数据的模板,效果很好,但我需要在一段时间后更新(重新渲染)相同的模板。在我的情况下,我在模板中有一个列表,如下所示:
template.html
<div id="template">
{{#list}}
<span>{{firstName}} {{lastName}} - {{phone}}</span>
{{/list}}
</div>
index.js
$(document).ready(function(){
$.ajax(
//some ajax here
).done(function(response){
loadTemplate(response);
});
});
function loadTemplate(data){
var template = $("#template").html();
Mustache.parse(template);
var render = Mustache.to_html(template, data);
$("#template").empty().html(render);
};
但是用户可以在此列表中添加更多元素,之后我需要更新胡子模板。我尝试调用Ajax(在列表中添加新值的响应)然后再次调用loadTemplate函数但不起作用,列表不会更改(更新)新值。
第一次渲染模板时,原始胡子模板会丢失。只有渲染的文本存在于同一位置。因此,第二次尝试重新渲染模板时,没有模板可以简单地渲染不再是模板的文本,因此文本只会再次输出。
解决方案是将您的原始模板存储在另一个位置(例如,在带有id=#originalTemplate
的元素内)。
然后做以下事项:
function loadTemplate(data){
var template = $("#originalTemplate").html(); // NOTE we use original template which does not get overriden
Mustache.parse(template);
var render = Mustache.to_html(template, data);
$("#template").empty().html(render);
};