Backbone.js - how to include an external HTML frag

2019-08-15 07:03发布

问题:

I have pre-rendered HTML fragments in my filesystem. Is it possible to load HTML fragments in backbone.js? I'm looking for something similar to ng-include of Angular.js

for example, in my file system (frag.html)

<h1>I'm a fragment</h1>

Should be injected to the template in a given placeholder location

<div id="ph">
   <!-- INJECTED -->
   <h1>I'm a fragment</h1>
</div>

回答1:

Suppose, we have this placeholder:

<div id="ph"></div>

and this HTML in frag.html file:

<div>
    <h1>I am</h1>
    <span>an HTML fragment</span>
</div>

Let us define our custom PrerenderedView with a special render method with the jQuery function load inside:

window.PrerenderedView = Backbone.View.extend({
  render: function() {
    this.$el.load(this.options.ajax_template_path, _.bind(this.onRender, this));
    return this;
  },
  onRender: function() {
    // do some stuff here, for example
    var h1 = this.$('h1');
    var text = this.model.get('some_value');
    setTimeout(function() {
      h1.text(text);
    }, 2000);
  }
});

At the moment of instantiation of the PrerenderedView we should pass an option ajax_template_path (which is 'frag.html' in our case).

$(function() {
  new window.PrerenderedView({
    el: $('#ph'),
    model: new Backbone.Model({some_value: 'It was'}),
    ajax_template_path: 'frag.html'
  }).render();
});

And, of course, we do not forget about Same Origin Policy if we are going to work without a server. For example, we can start chrome with the flag '--allow-file-access-from-files'.