lesimoes
lesimoes

Reputation: 936

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. In my case I have a list in template like this:

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

But the user can add more elements on this list, and after that I need to update the mustache template. 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.

Upvotes: 2

Views: 3047

Answers (1)

Nikos M.
Nikos M.

Reputation: 8325

The first time you render the template, the original mustache template gets lost. 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).

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

Upvotes: 5

Related Questions