alejandropascual
8/28/2011 - 11:35 AM

Quick jQuery plugin to load a Handlebars template into an element

Quick jQuery plugin to load a Handlebars template into an element

;(function($) {
  $.stacheComb = function(el, name, context, options) {

    var defaults = {
      container: 'body',
      path     : 'templates/'
    };

    var plugin = this;

    plugin.settings = {};

    var init = function() {
      plugin.settings = $.extend({}, defaults, options);
      plugin.el       = el;
      plugin.name     = name;

      $.when(plugin.loadTemplateSource())
       .then(function(source) {
         var template = Handlebars.compile(source);
         $(plugin.el).html(template(context));
       });
    };

    plugin.loadTemplateSource = function() {
      var settings  = plugin.settings,
          $template = $('script[data-template="'+plugin.name+'"]',
                        settings.container);

      if ($template.length) {
        // get template source from a script element
        return $template.html();
      } else {
        // get template source from external file
        return $.get(settings.path + plugin.name)
                .then(function(data) {
                  // store code into script element, for the future
                  $template = $('<script/>', {
                                  'type': 'text/x-handlebars-template',
                                  'data-template': plugin.name
                                }).html(data);
                  $template.appendTo(settings.container);
                })
                .promise();
      }
    };

    init();
  };

  $.fn.stacheComb = function(name, context, options) {
    var plugin = new $.stacheComb($(this), name, context, options);
    return $(this);
  };
})(jQuery);