Recommended jQuery templates for 2012?

JqueryHtmlJsonTemplates

Jquery Problem Overview


jQuery Templates have been deprecated for some time now.

I have some data in the form of a JavaScript object that I want to format as HTML and append to the DOM. What's the best way of doing that these days?

  1. Should I build up an HTML string?
  2. Should I create elements via jQuery such as $('<li>',{id:'my-'+Id}).append($('<span>').text(myText)) ?
  3. Is there a replacement or mature substitute for jQuery templates?

Jquery Solutions


Solution 1 - Jquery

This is how I do it in my projects:

Define a template in your HTML:

<script type="text/template" id="cardTemplate">
<div>
    <a href="{0}">{1}</a>
</div>
</script>

Use string.format to substitute variables:

var cardTemplate = $("#cardTemplate").html();
var template = cardTemplate.format("http://example.com", "Link Title");
$("#container").append(template);

string.format:

String.prototype.format = function() {
  var args = arguments;
  return this.replace(/{(\d+)}/g, function(match, number) { 
    return typeof args[number] != 'undefined'
      ? args[number]
      : match
    ;
  });
};

Pretty simple, you can even combine templates.

Solution 2 - Jquery

You should definitely try Handlebars and/or Mustache

I tend to use Handlebars but the syntax is quite similar.

Solution 3 - Jquery

Mustache.js is quite good for templating.

https://github.com/janl/mustache.js

Solution 4 - Jquery

Templates all the way, so much easier than trying to parse the JSON manually. Since I contributed to it, I'm partial to json2html as it doesn't require compiling of the templates AND uses nothing but JSON and JavaScript.

http://json2html.com

Solution 5 - Jquery

I realy don't like to build html element using javascript so I suggest you to use some template.
You can find a list of templates and a related question here.

I used to use jQuery Templates, it's prety simple but it's no longer actively.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionmpenView Question on Stackoverflow
Solution 1 - JquerysachleenView Answer on Stackoverflow
Solution 2 - JqueryAntonio LagunaView Answer on Stackoverflow
Solution 3 - JqueryJoeView Answer on Stackoverflow
Solution 4 - JqueryChad BrownView Answer on Stackoverflow
Solution 5 - JqueryRicardo Alvaro LohmannView Answer on Stackoverflow