如何从underscore.js JavaScript模板库引用名称中带有句点的JSON属性 [英] How to reference JSON attributes with a period in their name from underscore.js javascript template library

查看:96
本文介绍了如何从underscore.js JavaScript模板库引用名称中带有句点的JSON属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用下划线模板引擎(作为Backbone.js的一部分),并且存在一个问题,其中JSON对象的属性中带有句点,即

I am using underscore template engine (as part of Backbone.js) and have an issue where an attribute of the JSON object has a period in it i.e.

{
"id": 1234,
"company.id": 4321
}

当我尝试在下划线模板中访问此文件时,出现JavaScript错误:

When I try to access this in the underscore template I get a JavaScript error:

Company ID: <@= company.id @>

我想知道是否有可能以及如何完成访问带有句点的属性.我无权更改JSON的生成.

I'm wondering if it's possible and how it's done to access attributes with period in them. I'm not in a position to change the generation of the JSON.

推荐答案

一种简单的解决方法是在其周围包装另一个对象,以便您可以使用[]访问'company.id'.例如,您的模板可能如下所示:

An easy way around that is to wrap another object around it so that you can use [] to access 'company.id'. For example, your template could look like this:

<script id="tmpl" type="text/html">
    id: <%= o.id %><br>
    company: <%= o['company.id'] %>
</script>​

和您的JavaScript这样:

and your JavaScript like this:

var html = _.template($('#tmpl').html(), {
    o: {
        "id": 1234,
        "company.id": 4321
    }
});

演示: http://jsfiddle.net/ambiguous/wtLkP/1/ Underscore模板编译器使用with为模板中的<%= x %>之类的简单内容提供上下文,因此我认为您不能做得比上述o.技巧更好. Underscore通过您的模板构建一个函数,您可以通过查看该函数的source属性来查看该函数的源代码:

Demo: http://jsfiddle.net/ambiguous/wtLkP/1/ ​ The Underscore template compiler uses with to supply the context for simple things like <%= x %> in the templates so I don't think you're going to be able to do any better than the o. trick above. Underscore builds a function from your template, you can see the function's source by looking at the source attribute of the function:

var t = _.template(template_source);
console.log(t.source);

那会给你这样的东西:

function(obj){
var __p='';var print=function(){__p+=Array.prototype.join.call(arguments, '')};
with(obj||{}){
__p+='\n    id: '+
( o.id )+
'<br>company: '+
( o['company.id'] )+
' and stuff\n';
}
return __p;
}

,您会看到为什么仅<%= [x] %>无效的原因: 仅调整当前范围,而不能将[x]转换为有效的JavaScript.

and you can see why just <%= [x] %> won't work: with only adjusts the current scope, it can't make [x] into valid JavaScript.

这篇关于如何从underscore.js JavaScript模板库引用名称中带有句点的JSON属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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