Home > Article > Web Front-end > Why am I getting a Variable Not Defined Error in my Underscore Template?
Variable Not Defined Error in Underscore Template
You encountered an error when using underscore template in a Backbone.js view. The issue stems from the correct usage of template compilation in modern versions of Underscore.
In older versions of Underscore, you could use a one-step process to parse and fill in a template:
var html = _.template(template_string, data);
However, in Underscore 1.7.0 and later, the second argument to _.template is used for template options, necessitating a two-step process:
var tmpl = _.template(template_string);
var html = tmpl(data);
Or, in a one-liner:
var html = _.template(template_string)(data);
In your specific case, the corrected Backbone.js view render method would be:
var V = Backbone.View.extend({ el:'body', render: function () { var data = { lat: -27, lon: 153 }; var tmpl = _.template('<%= lat %> <%= lon %>'); this.$el.html(tmpl(data)); return this; } });
The above is the detailed content of Why am I getting a Variable Not Defined Error in my Underscore Template?. For more information, please follow other related articles on the PHP Chinese website!