How to reference JSON attributes with a period in their name from underscore.js javascript template library

前端 未结 1 1650
故里飘歌
故里飘歌 2021-01-25 16:09

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,
\"         


        
1条回答
  •  感情败类
    2021-01-25 16:16

    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.

    0 讨论(0)
提交回复
热议问题