Home >Web Front-end >JS Tutorial >Why Am I Getting an 'Underscore Template Rendering Error: Variable Not Defined'?

Why Am I Getting an 'Underscore Template Rendering Error: Variable Not Defined'?

Patricia Arquette
Patricia ArquetteOriginal
2024-11-23 10:05:17280browse

Why Am I Getting an

Underscore Template Rendering Error: "Variable Not Defined"

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:

  1. Compile the template using _.template.
  2. Execute the returned function to get the filled-in template.

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!

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