I wish to generate (or at least fill a template of some kind with JSON data and append to a list) a semi-complex HTML div element using jQuery. The data is in JSON format (if it matters) and for each parent entry I wish to add another div to a carousel-type element.
A long statement such as:
$('#list').append('<li><div id=" + entry.id +"><span id="highlight> + entry.name + <span/><div id="picture" ....
will work but is too hard to maintain (excuse errors there it's just to make a point). There must be a more efficient way.
Thanks.
You are looking into javascript templating languages - there are tons out there:
The idea is to keep data and its view separate:
var myUser = { name : 'John', lastname : 'Doe' };
$('#awesomeDiv').html(
someTemplateFunction( { user : myUser } )
);
And someTemplateFunction()
will hold in its body something like:
<p>Hello <strong><%=user.name %> <%=user.lastname %></strong></p>
By holding I mean that the template library is able to parse such template [coming from the DOM or from an external file] and to render it out to new DOM elements.
My pick is underscore.js because it's a very minimal yet useful library, feel free to look around.
You're looking for some templating. There are many:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With