Converting HTML Entities from JSON to String

[亡魂溺海] 提交于 2020-01-16 22:24:22

问题


I'm using polymer and I'm new to it (just started using it today) and I have some troubles displaying data coming from JSON like  , ’, &#8220 etc.

HTML

<news-card>        
    <h1>{{summary.title}}</h1>
    <img src="{{summary.thumbnail}}"></img>
    <span>{{summary.published}}</span>
    <p>{{summary.summary}}</p>
</news-card>

Ex. JSON:

{
 title: '&#8217; This is a title',
 thumbnail: 'test.jpg',
 published: 'October 15'
 summary: '&#8220; &nbsp; &nbsp;'
}

Ex. Output:

&#8217; This is a title
October 15
&#8220; &nbsp; &nbsp;

回答1:


I used custom filters to display the desired output.

HTML

<news-card>

    <h1>{{summary.title | encodeEntities}}</h1>
    <img src="{{summary.thumbnail}}"></img>
    <span>{{summary.published}}</span>

    <p>{{summary.summary | encodeEntities}}</p>
</news-card>

Script

Polymer('your-polymer-element-name', {
      encodeEntities: function(value) {
        var div = document.createElement('div');
        div.innerHTML = value;
        return div.innerHTML;
      }
  });

Sources:

Polymer - Expressions: Custom Filters

Stackoverflow - How to assign HTML entities in Polymer element definition?



来源:https://stackoverflow.com/questions/26385986/converting-html-entities-from-json-to-string

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!