Home > Web Front-end > JS Tutorial > Why Am I Getting an 'Underscore Template Variable Not Defined' Error in Backbone.js?

Why Am I Getting an 'Underscore Template Variable Not Defined' Error in Backbone.js?

Linda Hamilton
Release: 2024-12-02 16:05:17
Original
375 people have browsed it

Why Am I Getting an

Underscore Template Variable Not Defined Error Resolved

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.

The Issue

In the past, Underscore templates could be parsed and filled in a single step using the following syntax:

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

The Change

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.

The Solution

To compile and execute Underscore templates correctly, follow these steps:

  1. Compile the template using _.template(template_string).
  2. Execute the returned function with the data to fill in the template.

This can be represented as:

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

Example

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

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!

source:php.cn
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template