Underscore template throwing variable not defined error

匿名 (未验证) 提交于 2019-12-03 01:25:01

问题:

I've watched some videos on the topic of backbone js. This is an example straight from the video. It is from 2012, so I'm thinking backbone rules/library have changed, but I can't figure out why this does not work at the moment. In the video, the person shows it running in the JS Fiddle, but I can't get it to work. (I've included the necessary libraries in JS Fiddle, i.e. underscore, backbone and jQuery)

var V = Backbone.View.extend({   el:'body',   render: function () {   	var data = { lat: -27, lon: 153 };     this.$el.html(_.template(' ', data));     return this;   } });  var v = new V();  v.render();
  

回答1:

You used to be able to parse and fill in an Underscore template in one go like this:

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

But as of Underscore 1.7.0, the second argument to _.template contains template options:

template _.template(templateString, [settings])

Compiles JavaScript templates into functions that can be evaluated for rendering. [...] The settings argument should be a hash containing any _.templateSettings that should be overridden.

You have to compile the template using _.template and then execute the returned function to get your filled in template:

var tmpl = _.template(template_string); var html = tmpl(data);  // or as a one-liner, note where all the parentheses are var html = _.template(template_string)(data); 

In your case, it would look something like this:

var V = Backbone.View.extend({   el:'body',   render: function () {     var data = { lat: -27, lon: 153 };     var tmpl = _.template(' ');     this.$el.html(tmpl(data));     return this;   } });  var v = new V();  v.render();
   


回答2:

This can be useful

1: If you have more then one template or sometime you are using external template so it can be useful for you inside method you can write reusable code

var V = Backbone.View.extend({      el:'body',          temp: function (str) {              // reusable code             return _.template(str);         },         render: function () {             var data = { lat: -27, lon: 153 };              // calling your view method temp                     var tmpl = this.temp(' ');              this.$el.html(tmpl(data));              return this;         }      });      var v = new V();      v.render(); 


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!