简体   繁体   English

HandlebarsJS-带有特殊字符的JSON

[英]HandlebarsJS - JSON with special characters

I have a JSON-file which contains special characters and I want to display the JSON with HandlebarsJS but I cant get it to work: 我有一个包含特殊字符的JSON文件,我想用HandlebarsJS显示JSON,但无法正常工作:

the JSON structure is this: JSON结构是这样的:

{
  "feed" : {
      "entry" : {
          "title": {
              "$t" : "THIS TITLE I WANT"
           }
       }
}

I use BackboneJS , so inside my Collection I do: 我使用BackboneJS ,因此在我的收藏夹中可以:

parse: function(data) {
    return data.feed.entry    
}

So I tried to do 所以我尝试做

{{#each this}}

 <p>{{title.$t}}</p>

{{/each}}

But it doesnt work!?!?! 但这不起作用!?!?!

Can someone tell me what is wrong? 有人可以告诉我怎么了吗?

Actually, the suggestion from the user, who now has deleted his answer was right!! 实际上,现在删除了答案的用户的建议是正确的!

{{#each this}}

    <p>{{title.[$t]}}</p>

{{/each}}

Makes it work! 使它工作! So if you read this, post your answer again and I will accept it!! 因此,如果您阅读此内容,请再次发布您的答案,我会接受的!!

You're almost there but Handlebars handles loops over properties differently. 您快到了,但是Handlebars处理属性循环的方式有所不同。 Basically what's happening is that there's an implicit conversion of this in an each loop when dealing with objects. 基本上,这是怎么回事是,有一个隐式转换this与对象打交道时,在每个循环。

{{#each this}}
   //Here we think that **this** refers to an entry, but's it's not.
   //Cue implicit context switch to point **this** to the title object.
   //"unpack" it, and use the keys you're after.
   <p>{{$t}}</p> //voilà, we get the value.
{{/each}}

A very simple example is this ( JsBin here ): 这是一个非常简单的示例( 此处JsBin ):

<script id="cool" type="text/x-handlebars-template">
    {{#each this}}
      <p>{{socool}}</p>
    {{/each}}
</script>
var cool = {cool: {'socool': "brrr!!!" }};
var compiled = Handlebars.compile(document.getElementById("cool").innerHTML);

console.log(compiled(cool));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM