Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to load a Handlebars template via Ajax?

I would like to load additional templates on the fly. Is it possible?

like image 600
Mike Aski Avatar asked Feb 27 '12 17:02

Mike Aski


2 Answers

You can register new templates in Ember.TEMPLATES. They will then be available to views.

An excerpt from my code (jQuery Ajax handler):

success: function(data) {
  $(data).filter('script[type="text/x-handlebars"]').each(function() {
    templateName = $(this).attr('data-template-name');
    Ember.TEMPLATES[templateName] = Ember.Handlebars.compile($(this).html());
  });
}

That's it.

like image 71
Mike Aski Avatar answered Oct 01 '22 22:10

Mike Aski


I was just looking for the same thing and am about to have a play with the snippet below

credit: borismus on github https://gist.github.com/2165681

<script>
/*
 * Loads a handlebars.js template at a given URL. Takes an optional name, in which     case,
 * the template is added and is reference-able via templateName.
 */
function loadTemplate(url, name, callback) {
  var contents = $.get(url, function(templateText) {
    var compiledTemplate = Ember.Handlebars.compile(templateText);
    if (name) {
      Ember.TEMPLATES[name] = compiledTemplate
    } else {
      Ember.View.create({ template: compiledTemplate }).append();
    }
    if (callback) {
      callback();
    }
  });
}
</script>
like image 20
joevallender Avatar answered Oct 01 '22 22:10

joevallender