user578895
user578895

Reputation:

Is it possible to inject HTML into a polymer component via an attribute?

I'm using one of the core polymer components that basically has:

<polymer-element attributes="label">
    <div>{{label}}</div>

as part of the source. I'd like to inject some HTML into this so that it ultimately renders as:

<div>Item <small>Description</small></div>

Is there any way to do this without copying the entire component (which is basically impossible considering the dependency chain)?

Upvotes: 0

Views: 622

Answers (1)

ebidel
ebidel

Reputation: 24109

Polymer doesn't allow setting HTML inside {{}} expressions because it's a known XSS outlet. However, there are ways around it (1, 2).

I'm not sure there's a great way around this issue but I found something that works. You want to extend the element but also need to modify its shadow dom because of the .innerHTML limitation. Taking paper-button as an example, it has an internal {{label}}. You could extend the element, drill into its shadow dom, and set .innerHTML of the container where {{label}} is set. React to label changing (labelChanged) and call this.super():

<polymer-element name="x-el" extends="paper-button">
  <template>
    <shadow></shadow>
  </template>
  <script>
    Polymer('x-el', {
      labelChanged: function() {
        // When label changes, find where it's set in paper-button
        // and set the container's .innerHTML.
        this.$.content.querySelector('span').innerHTML = this.label;

        // call paper-button's labelChanged().
        this.super();
      }
  });
  </script>
</polymer-element>

Demo: http://jsbin.com/ripufoqu/1/edit

Problem is that it's brittle and requires you to know the internals of the element you're extending.

Upvotes: 2

Related Questions