Search code examples
javascriptlit-element

Lit-Element : Outputting Raw HTML from Property String


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


Solution

  • 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>