adequately good

decent programming advice

written by ben cherry

jQuery Micro-templates

John Resig wrote a neat micro-templating Javascript function a while back. I’ve been playing with this, and have discovered two things:

  1. These templates are totally nestable. Just make an element to be templated within a template, and call the sub-template code beneath the main call.

  2. I found myself tending to do lines like $("...").html(tmpl("...",{...})), which seemed clumsy. It was very easy to extend jQuery to include this templating engine (just add this underneath the existing code):

    jQuery.fn.tmpl = function(str,data){ return this.html(tmpl(str,data)); }

Then you can just do the following to templatize any number of elements:


I’m still playing with these templates, and working on a new project, so I hope to have more to write about it soon.

filed under javascript and jquery