Template not loading in a Backbone.js app - built

2019-04-13 05:09发布

问题:

I am using an .ejs template in my view. But for some reason the view does not load the given template. It returns undefined. Here's the code:

sandplate2.applicationView = Backbone.View.extend({
    el: 'div',

  template: _.template($("appl.ejs").html()),

  initialize: function(){
    console.log("Application view initialize");

    _.bindAll(this, "render");

    this.render();
  },

  render: function(){
    console.log("Application view rendering");
    this.$el.html(this.template());
    return this;
  }
});

Do I have to configure something else in order to load a template?

I structured my app using Yeoman. I used the init and backbone generators.

FYI - The template I am trying to load is loaded in the index.html using a script element.

回答1:

If you built it using Yeoman, take a look at app.js to see if you are using Backbone.LayoutManager. You might have to change the configuration there for EJS to work. By default, I think it should be expecting Underscore templates.

I'm using Handlebars and I updated my app.js to look like this:

Backbone.LayoutManager.configure({
  manage: true,

  paths: {
    layout: "templates/layouts/",
    template: "templates/"
  },

  fetch: function(path) {
    path = path + ".html";

    if (!JST[path]) {
      $.ajax({ url: app.root + path, async: false }).then(function(contents) {
        JST[path] = Handlebars.compile(contents);
      });
    }

    return JST[path];
  }
});

I also added Handlebars to the module's define() call, passing in 'Handlebars' as a reference. You might need to do something similar for EJS.



回答2:

Please try with latest backbone genearator with yeoman 1.0beta. We have made lot of improvements on it including Precompiling ejs templates. You don't want to worry about templates, yeoman will precompile and load it for you.

A sample generated code for input-view is provided below.

Todo.Views.InputView = Backbone.View.extend({

    template: JST['app/scripts/templates/input.ejs'],

    render: function(){
       $(this.el).html(this.template());
    }

});


回答3:

Conventions aside, it looks like the problem is simply your jQuery lookup.

_.template($("appl.ejs")...

$('appl.ejs') isn't a valid DOM selector unless you have an element like this in your index.html

<appl class="ejs"></appl>

If you're trying to target your template with jQuery, give it an ID or something that jQuery can find like so:

<script type="text/template" id="appl">
    <div></div><!-- template html here -->
</script>

    // later...
    $('#appl').html()
    // will get your template html

However, as others have mentioned, in a yeoman and require.js workflow, you can ask require.js to fetch the template for you as text and throw it around as a variable before creating an underscore template.