Home  >  Article  >  Web Front-end  >  Why am I getting a Variable Not Defined Error in my Underscore Template?

Why am I getting a Variable Not Defined Error in my Underscore Template?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-11-19 00:21:02952browse

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:

  1. Compile the template:
var tmpl = _.template(template_string);
  1. Execute the compiled function with data:
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!

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