0

所以基本上我从 WoW(魔兽世界)API 得到一个 JSON 响应:

            this.url="http://eu.battle.net/api/wow/character/"+config.realm+"/"+config.charName+"fields=achievments&jsonp=?";

            this.template = config.template.html();

            $.when(this.fetch()).then(function(response){
                console.log( response );
                self.attachTemplate( response );
            });
        },

        attachTemplate: function( data ){

            var compTemplate = _.template( this.template, data );

            console.log( compTemplate );

            this.getContainer().append( compTemplate );
        },

我的模板如下所示:

<h1><%=name%></h1>
<h5 style="color: black;"><strong style="color: black;"><%= class %></strong>

我越来越

Uncaught SyntaxError: Unexpected reserved word 

显然我不能使用“类”这个词,因为它是一个 js 保留字。API 响应对象有一个名为 class 的字段。除了创建中间变量之外,还有其他解决方法吗?

4

2 回答 2

2

您可以将您的对象包装data在另一个对象中,以解决由下划线使用引起的冲突with

var compTemplate = _.template( this.template, { 'wrap': data } );

或者(可能是更好的方法),是variable为模板指定一个名称,该名称将告诉下划线不要使用with,并将自动将所有数据放入具有您指定名称的对象中。这种方法也会使性能稍微好一点:

var compTemplate = _.template( this.template, data, { 'variable': 'wrap' } );

然后在您的模板中,您必须为所有变量引用添加前缀wrap.

<h1><%= wrap.name %></h1>
<h5 style="color: black;"><strong style="color: black;"><%= wrap.class %></strong>
于 2013-04-15T17:34:49.010 回答
1

我编写了一个完整的 JS 库来使用 WOW API。它位于此处:https ://github.com/eduardm/wowjsapi

于 2013-11-05T08:26:04.237 回答