Underscore1.5.0 API学习(template)

翻译参照:http://www.css88.com/doc/underscore/

强烈推荐:http://hi.baidu.com/cloud_idea/item/b1952a61a8ccd101a1cf0fbe


template   _.template(templateString, [context])


将 JavaScript 模板编译为可以渲染的函数。 可通过json数据源渲染复杂的HTML。Template函数可以插入变量值(<%=...%>),也可以运行任意的JS代码(<%..%>)。如果你想要


If you wish to interpolate a value, and have it be HTML-escaped, use <%- … %> When you evaluate a template function, pass in a data object that has properties corresponding to the template's free variables. If you're writing a one-off, you can pass the data object as the second parameter to template in order to render immediately instead of returning a template function. The settings argument should be a hash containing any _.templateSettings that should be overridden.

模板函数可以是以下两种内部变量:使用<%= … %>,以及用<% … %>执行任意 JavaScript 代码。如果您想插入一个值,它将 HTML 转义,当你使用<%- … %> 评估模板函数,在传递有对应于该模板的属性变量context。如果你在写一次过,你可以传递context作为 template 的第二个参数,以便立即呈现而不是返回的模板函数。
Compiles JavaScript templates into functions that can be evaluated for rendering. Useful for rendering complicated bits of HTML from JSON data sources. Template functions can both interpolate variables, using
<%= … %>, as well as execute arbitrary JavaScript code, with <% … %>. If you wish to interpolate a value, and have it be HTML-escaped, use <%- … %> When you evaluate a template function, pass in a context object that has properties corresponding to the template's free variables. If you're writing a one-off, you can pass the context object as the second parameter to template in order to render immediately instead of returning a template function.

var compiled = _.template("hello: <%= name %>");
compiled({name : 'moe'});
=> "hello: moe"

var list = "<% _.each(people, function(name) { %> <li><%= name %></li> <% }); %>";
_.template(list, {people : ['moe', 'curly', 'larry']});
=> "<li>moe</li><li>curly</li><li>larry</li>"

var template = _.template("<b><%- value %></b>");
template({value : '<script>'});
=> "<b>&lt;script&gt;</b>"

您还可以使用 JavaScript 代码内print 。这是有时比使用<%= ... %>更方便 .

var compiled = _.template("<% print('Hello ' + epithet); %>");
compiled({epithet: "stooge"});
=> "Hello stooge."

If ERB-style delimiters aren't your cup of tea, 您可以更改下划线的模板设置,使用不同的符号来表示插值的代码。定义 interpolate 正则表达式,和 (可选)evaluate正则表达式来匹配,但是必须分别是inserted 和 evaluated,如果不提供evaluate正则表达式,您的模板将只能够的插补值。 例如, 看看 Mustache.js 样式模板:

_.templateSettings = {
  interpolate : /\{\{(.+?)\}\}/g
};

var template = _.template("Hello {{ name }}!");
template({name : "Mustache"});
=> "Hello Mustache!"
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值