简体   繁体   English

使用 Mustache js 更新模板

[英]Update a template with Mustache js

I`m using mustache js to render a template with data from API and works nice, but i need to update (re-render) same template after a while.我正在使用 mustache js 来渲染带有来自 API 的数据的模板并且效果很好,但是我需要在一段时间后更新(重新渲染)相同的模板。 In my case I have a list in template like this:就我而言,我在模板中有一个列表,如下所示:

template.html模板.html

<div id="template">
  {{#list}}
    <span>{{firstName}} {{lastName}} - {{phone}}</span>
  {{/list}}
</div>

index.js索引.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);
};

But the user can add more elements on this list, and after that I need to update the mustache template.但是用户可以在此列表中添加更多元素,之后我需要更新 mustache 模板。 I tried call the Ajax (that response with new value add on the list) then call loadTemplate function again but does not work, the list does not change (update) with new values.我尝试调用 Ajax(该响应在列表中添加了新值),然后再次调用 loadTemplate 函数但不起作用,列表不会使用新值更改(更新)。

The first time you render the template, the original mustache template gets lost.第一次渲染模板时,原始的 mustache 模板丢失了。 ONLY the rendered text exists in same location.只有呈现的文本存在于同一位置。 So the second time you try to re-render the template there is no template to render simply text that is NOT a template anymore so the text is simply outputed again.因此,当您第二次尝试重新渲染模板时,没有模板可以渲染不再是模板的简单文本,因此文本只是再次输出。

The solution is to store your original template in another location (eg inside an element with id=#originalTemplate ).解决方案是将您的原始模板存储在另一个位置(例如,在id=#originalTemplate的元素内)。

Then do following:然后执行以下操作:

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);
};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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