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,
\"
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:
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 )+
'
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.