Adding elements to mustache.js templates
I’ve been experimenting with Mustache.js to do templating for a JavaScript project of mine. One thing that I’m having trouble with is that there’s no way to add more dynamic elements to the resulting template. The output is an HTML string.
What I want to do is to insert HTMLElements into a layout I created using Mustache.js.
Being inspired by the Mustache.js partials I came up with this function to run after I’ve constructed my template:
var to_elements = function(html, elements) {
var result = $(html)[0];
for(element in elements) {
$("#"+element, result).replaceWith(elements[element]); }
return result;
};
It will run and replace all elements with an id that matches a the members of the object I provided. Here’s an example usage:
var layout = to_elements("<div><div id='form'></div><div id='list'></div></div>", { form : createProject.element, list : projectList.element });
This will produce the following output:
<div>
<div class="form">
<input type="text">
<button>+</button>
</div>
<div class="list">
<div>aaaa</div>
<div>test</div>
</div>
</div>
This output however is in the form of HTMLElements where I’ve attached all events and handling, allowing me to test the individual parts of the individually using templates to coordinate everything together at the end.