使用 Mustache js 更新模板
Update a template with Mustache js
我正在使用 mustache 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);
};
我正在使用 mustache 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);
};