Recommended jQuery Templates for 2012?

JQuery templates have been deprecated for some time.

I have some data as a JavaScript object that I want to format as HTML and add to the DOM. What is the best way to do this these days?

  • Should I create an HTML string?
  • Should I create elements via jQuery, for example $('<li>',{id:'my-'+Id}).append($('<span>').text(myText)) ?
  • Is there a replacement or mature replacement for jQuery templates?
+54
json jquery html templates
Dec 27 '12 at 22:55
source share
5 answers

Here's 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 replace 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 patterns.

+104
Dec 27 '12 at 23:01
source share

You should try Handlebars and / or Mustache

I use Handlebars, but the syntax is very similar.

+10
Dec 27
source share

Mustache.js is good for templates.

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

+9
Dec 27 '12 at 22:57
source share

Templates are complete, it’s easier than trying to parse JSON manually. Since I contributed to this, I partially relate to json2html, as it does not require compilation of templates and uses nothing but JSON and JavaScript.

http://json2html.com

+7
Dec 28 '12 at 5:24
source share

I really don't like creating an html element using javascript, so I suggest you use some kind of template.
You can find a list of templates and a related question here .

I used to use jQuery Templates , it is simple, but it is inactive.

0
Dec 27 '12 at 23:01
source share



All Articles