使用 Mustache js 更新模板

les*_*oes 2 javascript mustache

我正在使用 mustache js 来渲染带有来自 API 的数据的模板并且效果很好,但我需要在一段时间后更新(重新渲染)相同的模板。就我而言,我在模板中有一个列表,如下所示:

模板.html

<div id="template">
  {{#list}}
    <span>{{firstName}} {{lastName}} - {{phone}}</span>
  {{/list}}
</div>
Run Code Online (Sandbox Code Playgroud)

索引.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);
};
Run Code Online (Sandbox Code Playgroud)

但是用户可以在此列表中添加更多元素,之后我需要更新 mustache 模板。我尝试调用 Ajax(在列表中添加新值的响应),然后再次调用 loadTemplate 函数但不起作用,列表不会使用新值更改(更新)。

Nik*_* M. 5

第一次渲染模板时,原始的 mustache 模板丢失了。 只有呈现的文本存在于同一位置。因此,当您第二次尝试重新渲染模板时,没有模板可以渲染不再是模板的简单文本,因此文本只是再次输出。

解决方案是将您的原始模板存储在另一个位置(例如在带有 的元素内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);
};
Run Code Online (Sandbox Code Playgroud)