Wednesday, December 19, 2012

Easy MicroTemplating

I'm a huge fan of templates in that I always want to separate my view from my code. But I don't like to include hundreds of kilobytes of some library just to get templating - so I made my own in a few lines which I can just copy into any project.

The most basic usage is to pass it data and a template and get the result:
microTemplate({name:'Jack'}, '<h1>Hello {{name}}</h1>');
This will return:
<h1>Hello Jack</h1>

Now there are different ways of using it. You can specify a DOM element which contains your template so if you have this in your HTML:
<div id="op"><h1>Hello {{name}}</h1></div>
You can just do:
microTemplate({name:'Jack'}, $('#op')[0]);
This will automatically write the result back into your div.

It supports arrays so:
var friends = [{name:'Jack'},{name:'Jill'}];
microTemplate(friends, '<h1>Hello {{name}}</h1>', $('#op3')[0]);
Will result in:
<h1>Hello Jack</h1>
<h1>Hello Jill</h1>

If you want a table or an ordered list you'll need to specify header and footer:
microTemplate(friends, '<li>{{name}}</li>', $('#op4')[0], '<ol>', '</ol>');
Which will result in:

I think it's awesome!

<!doctype html>
  <script src=""></script>
  $(function() {
    microTemplate({name:'Jack'}, $('#op')[0]);
    microTemplate({name:'Jack'}, '<h1>Hello {{name}}</h1>', $('#op2')[0]);
    microTemplate([{name:'Jack'},{name:'>>Jill<<'}], '<h1>Hello {{name}}</h1>', $('#op3')[0]);
    microTemplate([{name:'Jack'},{name:'Jill'}], '<li>{{name}}</li>', $('#op4')[0], '<ol>', '</ol>');
  function microTemplate(data, temp, el, head, foot) {
    if (typeof temp.innerHTML=='string') {el=temp;temp=temp.innerHTML;}
    data = [].concat(data);
    var res = head||'';
    for (var i in data) {
      res += temp;
      for (var f in data[i]) {
        res = res.replace(new RegExp('{{{'+f+'}}}', 'ig'), data[i][f]);
        res = res.replace(new RegExp('{{'+f+'}}', 'ig'), data[i][f].replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;'));
    res += foot||'';
    if (el && typeof el.innerHTML == 'string') el.innerHTML = res;
    return res;

<div id="op"><h1>Hello {{name}}</h1></div>
<div id="op2"></div>
<div id="op3"></div>
<div id="op4"></div>


No comments:

Post a Comment