1
votes

I am using backbone with underscore templates, but I'm having problem getting underscore to render the data I pass along to the template. Here's my code:

define([
  'jquery',
  'underscore',
  'backbone',
  'models/home/HomeModel',
  'text!/app/templates/home/homeTemplate.html'
], function($, _, Backbone,HomeModel,homeTemplate){

  var HomeView = Backbone.View.extend({
    el: $("#page"),

    initialize: function(){
      var self = this;
      self.model = new HomeModel();
    },

    render: function(){
      var homeTitle = this.model.get('title');
      var homeData = {
        title: homeTitle
      }

      var compiledTemplate = _.template( homeTemplate, homeData );
      this.$el.html(compiledTemplate);

    }

  });

  return HomeView;

});

In this code, I can get all the way to the var homeData = {} object, which includes the proper title from the model, but when I create the compiledTemplate, I get an error saying title is not defined.

Any ideas what I'm doing wrong here?

1
have you verified your homeData has what you expect? what does your template look like?kinakuta

1 Answers

2
votes

From the Underscore.js documentation

var compiled = _.template("hello: <%= name %>");

compiled({name: 'moe'});

=> "hello: moe"

It looks like you are not using the _.template method correctly. It returns a compiled template function that you can call with the data to render:

var compiledTemplate = _.template( homeTemplate, homeData );
this.$el.html( compiledTemplate( homeData ) );