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
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:and your JavaScript like this:
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 theo.
trick above. Underscore builds a function from your template, you can see the function's source by looking at thesource
attribute of the function:That will give you something like this:
and you can see why just
<%= [x] %>
won't work:with
only adjusts the current scope, it can't make[x]
into valid JavaScript.