10

I'm new to Lit-Element and am having trouble outputting raw HTML when passed as a property string. I'm guessing there is a better way of accomplishing this and any help would be appreciated.

JS Fiddle showing my problem here: https://jsfiddle.net/32dnvkwq/

<script src="https://unpkg.com/@webcomponents/webcomponentsjs@next/webcomponents-loader.js"></script>

<script type="module">
  import {LitElement, html} from 'https://unpkg.com/@polymer/lit-element@latest/lit-element.js?module';

  class MyElement extends LitElement {

      static get properties() { 
        return { str: String }
     }

    render() {
      return html `${this.str}`;
    }  
  }

  customElements.define('my-element', MyElement);
</script>

<my-element str="line1<br />line2"></my-element>

Output:

line1<br />line2

iamjpg
  • 7,078
  • 1
  • 16
  • 18

2 Answers2

19

This is a dangerous operation so you have to explicitly opt-in to allowing rendering HTML. Make sure your HTML is safe and not set by users. You have to import the unsafeHTML directive from lit-html and wrap this.str in it.

<script src="https://unpkg.com/@webcomponents/webcomponentsjs@next/webcomponents-loader.js"></script>

<script type="module">
  import {LitElement, html} from 'https://unpkg.com/@polymer/lit-element@latest/lit-element.js?module';
  import {unsafeHTML} from 'https://unpkg.com/lit-html@latest/directives/unsafe-html.js?module';

  class MyElement extends LitElement {

      static get properties() { 
        return { str: String }
     }

    render() {
      return html `${unsafeHTML(this.str)}`;
    }  
  }

  customElements.define('my-element', MyElement);
</script>

<my-element str="line1<br />line2"></my-element>
kjhughes
  • 106,133
  • 27
  • 181
  • 240
abraham
  • 46,583
  • 10
  • 100
  • 152
8

I figured out a workaround using document fragments. Not sure if it's ideal, but it works as expected.

JS Fiddle showing solution: https://jsfiddle.net/1whj0cdf/

<script src="https://unpkg.com/@webcomponents/webcomponentsjs@next/webcomponents-loader.js"></script>

<script type="module">
  import {LitElement, html} from 'https://unpkg.com/@polymer/lit-element@latest/lit-element.js?module';

  class MyElement extends LitElement {

      static get properties() { 
        return { str: String }
     }

    returnString() {
        var frag = document.createRange().createContextualFragment(`${ this.str }`);
      return frag;
    }

    render() {
      return html `${ this.returnString() }`;
    }  
  }

  customElements.define('my-element', MyElement);
</script>

<my-element str="line1<br />line2"></my-element>
iamjpg
  • 7,078
  • 1
  • 16
  • 18