简体   繁体   中英

Converting HTML tags from JSON-String into real HTML Elements

I created a custom Element wich gets data from a JSON file:

<polymer-element name="view-component" attributes="number">
<template>
    <link rel="stylesheet" href="custom_style.css" type="text/css">

    <core-ajax auto
    response="{{data}}"
    on-core-response="{{ajaxHandler}}"

    url="http://www.test.com/json/{{number}}"; 

    handleAs="json"></core-ajax>

    <div class="showbox">

    <p><b>entry:</b> {{data.entry| encodeEntities}}</p>
 </template>

The data.entry String looks like this: <p>MyBrand&trade; is <b>very<\\b> nice <\\p> <p>MyBrand&trade; is <b>very<\\b> nice <\\p>

After finding this Question:

Converting HTML Entities from JSON to String

my String looks like this: <p> MyBrand™ is <b> very <\\b> nice <\\p>

But How do I parse the actual Elements in that String and add them to my Custom Element?

Here is my JavaScript Code so far:

Polymer('view-component', {

  encodeEntities: function(value) {

    console.log(value);
    var div = document.createElement('div');
    div.innerHTML = value;
    console.log(div.childNodes[0]);
    return div.innerHTML;

  },

My console log console.log(div.childNodes[0]); puts out a DOM-Tree which looks perfect! But when I want to return it to the component, the Browser renders : [object HTMLParagraphElement] instead of attaching the DOM to my element.

What am I missing? Any help is appreciated!

Polymer escapes injected data by default for security considerations. (see Advanced Topics – Data Binding ). You will thus have to use the injectBoundHtml method. To do this, you should give your <p> tag an id and add the content using injectBoundHtml , for example in the ready callback:

Polymer({
  ready: function() {
    this.injectBoundHTML('<b>entry:</b> {{data.entry}}', 
                         this.$.your_paragraph_id);
  }
});


Two asides:

  1. You don't need to specify the name of the element in the Polymer() call if you are including the script within the <polymer-element> tag.
  2. I think you're missing the declaration of the data attribute, unless you've put it in the publish object or something.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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