How to load external template synchronously with backbone

我的未来我决定 提交于 2019-12-01 14:15:13

i load my templates this way:

         $.ajax({
            url     : 'my/template.tpl',
            async   : false,
            success : function(tpl) {
                //do something with the template
            }
        });

maybe it`s a solution that works also for you ..

I did this :

class HomeView extends Backbone.View
  template: ->
    template = "views/home.html"
    cache = window.templates[template]
    return cache if cache

    cache = $.ajax(
      url: "views/home.html"
      async: false).responseText

    window.templates[template] = cache
    return cache

  render: ->
    @$el.html(@template())

And, in my application's initalization :

window.templates = {}

So I can load template asynchronously and cache it. Obviously, I will do some refactoring and, may be, place it into a JQuery function.

Thanks for yours helps.

Edit

I change my code to do this :

class Loader
  @files: {}
  @load: (path) ->
    return @files[path] ||= $.ajax(url: path, async: false).responseText

Now I can do this :

class HomeView extends Backbone.View
  template: ->
    Loader.load("views/home.html")

  render: ->
    @$el.html(@template())

This is the javascript's version :

var Loader;

Loader = (function() {

  function Loader() {}

  Loader.files = {};

  Loader.load = function(path) {
    var _base;
    return (_base = this.files)[path] || (_base[path] = $.ajax({
      url: path,
      async: false
    }).responseText);
  };

  return Loader;

})();

I will probably publish the code on github...

user123444555621

If your application runs as a phonegap app, you might as well include your templates in the HTML:

Explanation of <script type = "text/template"> ... </script>

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