In Backbone.js, using Underscore templates to dynamically generate HTML is common, but earlier code snippets may encounter "variable not defined" errors. This article explains why this occurs and how to resolve it.
In the past, Underscore templates could be parsed and filled in a single step using the following syntax:
var html = _.template(template_string, data);
However, Underscore versions 1.7.0 and above introduced the concept of template options, which must be explicitly provided as the second argument to _.template(). These options allow for fine-grained control over template behavior.
To compile and execute Underscore templates correctly, follow these steps:
This can be represented as:
var tmpl = _.template(template_string); var html = tmpl(data);
Consider the following code snippet, which shows how to implement templates with Airbnb's Vacation Rentals dataset:
var V = Backbone.View.extend({ el: 'body', render: function() { var data = [ { id: 1, lat: -27, lon: 153 }, { id: 2, lat: -33, lon: 151 } ]; var tmpl = _.template('<li><%= id %>. <%= lat %>, <%= lon %></li>'); var html = data.map(tmpl).join(''); this.$el.html(html); return this; } }); var v = new V(); v.render();
By following the correct template syntax, you can effectively use Underscore templates in your Backbone.js applications.
The above is the detailed content of Why Am I Getting an 'Underscore Template Variable Not Defined' Error in Backbone.js?. For more information, please follow other related articles on the PHP Chinese website!