Home >Web Front-end >JS Tutorial >Why am I getting an 'Underscore Template Error: Variable not defined' in my Backbone.js code?

Why am I getting an 'Underscore Template Error: Variable not defined' in my Backbone.js code?

DDD
DDDOriginal
2024-11-13 06:11:02905browse

Why am I getting an

Underscore Template Error: "Variable not defined"

In the provided example for Backbone.js, an error is encountered when using the Underscore template. The error message reads "Variable not defined." To understand the issue and resolve it, let's delve into the usage of Underscore templates.

In older versions of Underscore (prior to version 1.7.0), the second argument to the _.template function was used to provide data for the template. This allowed for a concise syntax where the template and data could be specified in a single line.

However, as of Underscore version 1.7.0, the second argument to _.template has been repurposed to accommodate template options. This means that the previous method of specifying data directly in the second argument is no longer valid.

To fix the issue, it is necessary to compile the Underscore template using the _.template function and then execute the resulting function to get the filled-in template. The correct syntax is:

var tmpl = _.template(template_string);
var html = tmpl(data);

In the case of the provided Backbone.js example, the following code would resolve the error:

render: function () {
  var data = { lat: -27, lon: 153 };
  var tmpl = _.template('<%= lat %> <%= lon %>');
  this.$el.html(tmpl(data));
  return this;
}

By compiling the template first and then executing it with the specified data, the error "Variable not defined" will be eliminated, allowing the template to render the correct content.

The above is the detailed content of Why am I getting an 'Underscore Template Error: Variable not defined' in my Backbone.js code?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn