Is it possible to load a Handlebars template via Ajax?

人盡茶涼 提交于 2019-11-26 16:00:32

问题


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


回答1:


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.




回答2:


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>



回答3:


I am using requirejs along with text plugin to load handlebar templates dynamically.

r.js optimizer will compile the handlerbar template to text file, which can be loaded easily using requirejs or even ajax



来源:https://stackoverflow.com/questions/9469235/is-it-possible-to-load-a-handlebars-template-via-ajax

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!