Home > Web Front-end > JS Tutorial > 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
Release: 2024-11-19 00:21:02
Original
1057 people have browsed it

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);
Copy after login

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);
Copy after login
  1. Execute the compiled function with data:
var html = tmpl(data);
Copy after login

Or, in a one-liner:

var html = _.template(template_string)(data);
Copy after login

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;
  }
});
Copy after login

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 of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template