The jQuery fromTemplate plugin

We started using the Micro-Templating concept by John Resig to separate HTML markup from Javascript code in JSON based applications like our online crm solution. This concept solves the problem of outputting ugly strings of HTML very nicely, but the original code snippit was a little hard to understand for those of us who are not Javascript Ninjas (a book by John Resig). To fix this I had created a simple jQuery plugin and refactored the code a little.

This resulted in the following easy to use plugin:

$("#someElement").fromTemplate("templateId", dataset)

Where templateId is the ID of the template element and dataset is a simple Javascript object with data to expose to the template. Because this might help others understand the Micro-Templating code a bit better and might be useful to other jQuery users I have just uploaded the code to github as jQuery-fromTemplate-plugin.

Comments

  • Date-time February 4th, 2010 at 23:50 - Author Vladimiro Casinha - Link

    Hi,

    great simple and effective tool you’ve made.
    Just to let you know that I’m having issues with Internet Explorer, maybe you too. :)

    I’ll keep looking here for news.

    Thank you once again!

  • Date-time February 5th, 2010 at 00:37 - Author Koen Bos - Link

    Hi Vladimiro,

    There is indeed a minor bug in IE, but i have found the problem.

    It should work if you replace line 34:
    tmpl = document.getElementById(opt.templatePrefix + str).textContent;
    by:
    tmpl = $(’#’ + opt.templatePrefix + str).html();

    I will notify Tomas so the version on github also get’s an update.

    Koen

  • Date-time February 5th, 2010 at 09:03 - Author Tomas Salfischberger - Link

    I have updated the code on github, thanks for the heads up.

    Tomas

  • Date-time February 21st, 2010 at 03:08 - Author Lorenzo Dee - Link

    Hi Tomas,

    Thank you so much for this very helpful jQuery plugin. I’ve extended it by adding a static method for those cases when the resulting HTML is needed (and not necessary to be placed into an element). This allows me to do a $.fromTemplate(…) and assign the returned HTML to a variable (instead of replacing an element’s html). It continues to support the usual $(’selector’).fromTemplate(…) calls.

    I made the following changes:

    (function($) {
    /* Public static function (added) */
    $.fromTemplate = function(str, data, options) {
    var settings = $.extend({}, $.fn.fromTemplate.defaults, options);
    return renderTemplate(str, settings, data);
    };

    /* Public function on jQuery elements */
    $.fn.fromTemplate = function(str, data, options) {
    return this.each(function(){
    $(this).html($.fromTemplate(str, data, options));
    });
    };

    /* Default settings */
    . . .

    Thank you once again!

Leave a Reply