Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery to dynamically create complex HTML fragments

Tags:

json

html

jquery

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.

like image 645
adamK Avatar asked Sep 03 '12 01:09

adamK


2 Answers

You are looking into javascript templating languages - there are tons out there:

  • underscore.js;
  • mustache.js;
  • jade;
  • handlebars.js;
  • many more...

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.

like image 64
moonwave99 Avatar answered Nov 03 '22 03:11

moonwave99


You're looking for some templating. There are many:

  • Handlebars
  • Hogan
  • dust.js
  • Mustache
  • underscore templates
  • jQuery templates
like image 1
Austin Greco Avatar answered Nov 03 '22 03:11

Austin Greco