下划线模板抛出变量未定义错误 [英] Underscore template throwing variable not defined error

查看:19
本文介绍了下划线模板抛出变量未定义错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我看过一些关于主干 js 主题的视频.这是直接来自视频的示例.它是从 2012 年开始的,所以我认为主干规则/库已经改变,但我不知道为什么现在这不起作用.在视频中,该人显示它在 JS Fiddle 中运行,但我无法让它工作.(我已经在 J​​S Fiddle 中包含了必要的库,即下划线、主干和 jQuery)

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('<%= lat %> <%= lon%>', data));
    return this;
  }
});

var v = new V();

v.render();

<script src="http://underscorejs.org/underscore-min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="http://backbonejs.org/backbone-min.js"></script>

推荐答案

你曾经可以像这样一次性解析和填充 Underscore 模板:

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

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

但从 Underscore 1.7.0 开始,_.template 包含模板选项:

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

模板 _.template(templateString, [settings])

将 JavaScript 模板编译为可用于渲染的函数.[...] settings 参数应该是一个哈希值,其中包含任何应该被覆盖的 _.templateSettings.

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.

您必须使用_.template 编译模板,然后执行返回的函数以获取填充的模板:

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('<%= lat %> <%= lon %>');
    this.$el.html(tmpl(data));
    return this;
  }
});

var v = new V();

v.render();

<script src="//cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script>

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/backbone.js/1.1.0/backbone-min.js"></script>

这篇关于下划线模板抛出变量未定义错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆