How to inject HTML into a template with polymer

一曲冷凌霜 提交于 2019-12-17 04:33:11

问题


I'm using polymer-jsonp to perform JSONP requests, but the response sometimes contains html.

For example, supposing that post.content is "<strong>Foo</strong> bar", how can I display {{post.content}} such that "Foo" is in bold?

<polymer-element name="feed-element" attributes="">
  <template>
    <template repeat="{{post in posts.feed.entry}}">
      <p>{{post.content}}</p>
    </template>
    <polymer-jsonp url="url" response="{{posts}}"></polymer-jsonp>
  </template>
  <script>
    Polymer('feed-element', {
      created: function() { },
      attached: function() { },
      detached: function() { },
      attributeChanged: function(attrName, oldVal, newVal) { }
    });
  </script>
</polymer-element>

回答1:


Polymer will not stamp unescaped HTML via data-binding because it becomes a vulnerability for XSS attacks.

There are talks ongoing about making it possible to stamp HTML under limited circumstance, or to allow for customized filtering, but this is not implemented yet at the data layer.

It is possible to do what you want today using an additional custom element, but again, be advised of the potential for bad things to happen if you render untrusted HTML into your page.

Here is an example that shows this technique:

http://jsbin.com/durajiwo/1/edit




回答2:


For those look for polymer 1.0

<dom-module id="html-echo">
  <style>
    :host {
      display: block;
    }
  </style>
  <template>
  </template>
</dom-module>

<script>
  (function () {
    Polymer({
      is: 'html-echo',
      properties: {
        html: {
          type: String,
          observer: '_htmlChanged'
        }
      },
      _htmlChanged: function (neo) {
        // WARNING: potential XSS vulnerability if `html` comes from an untrusted source
        this.innerHTML = neo;
      }
    });
  })();
</script>



回答3:


If you're sure it is what you want to do, just use innerHTML.

_renderHtml: function(html) {
  this.$.dynamicHtmlContainer.innerHTML = html;
}

Or to dynamically add a shadow-dom child:

_renderHtml: function(html) {
  var div = document.createElement('div');
  div.innerHTML = html;
  Polymer.dom(this).appendChild(div);
}

I think Polymer.dom is being removed in Polymer 2.0 though.



来源:https://stackoverflow.com/questions/22199662/how-to-inject-html-into-a-template-with-polymer

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