How to reference JSON attributes with a period in

2020-04-22 02:01发布

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
}

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

Company ID: <@= company.id @>

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.

cowper

1条回答
该账号已被封号
2楼-- · 2020-04-22 02:35

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>​

and your JavaScript like this:

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

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);

That will give you something like this:

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;
}

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

查看更多
登录 后发表回答