Problem:
You're trying to use an Underscore template to render HTML, but encountering the error "Variable Not Defined." The code you're using is:
var V = Backbone.View.extend({ el:'body', render: function () { var data = { lat: -27, lon: 153 }; this.$el.html(_.template('<%= lat %> <%= lon%>', data)); return this; } }); var v = new V(); v.render();
Answer:
The issue lies with how Underscore templates are rendered. In previous versions of Underscore, you could parse and fill in a template in one go, but in modern versions, this has changed.
To resolve the error, you need to:
Here's how the code should look like:
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; } }); var v = new V(); v.render();
This updated code will correctly render the template using the provided data.
The above is the detailed content of Why Am I Getting an 'Underscore Template Rendering Error: Variable Not Defined'?. For more information, please follow other related articles on the PHP Chinese website!