Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Recommended jQuery templates for 2012? [duplicate]

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.


You should definitely try Handlebars and/or Mustache

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


Mustache.js is quite good for templating.

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


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