Search code examples
javascripthtmlpolymerlit-html

Polymer 3: Text to HTML


In my Polymer page I get a text from db in a variable and the text contains HTML tags. How can I change this text to HTML formated? The text I get is something like following:

<h1>Header</h1>
<p>More text......</p>
<a href="http://www.google.com">Read more</a>

I display it in my page like the following, where item.content has the above text:

<div>
  <p>${item.content}</p>
</div>

Solution

  • You can use unsafeHTML function from lit-html lib. See API reference here.

    Example:

    import { unsafeHTML } from 'lit-html/directives/unsafe-html.js'
    
    ...
    
    _render ({ yourHtmlString }) {
      return html`
        ${unsafeHTML(yourHtmlString)}
      `
    }
    

    Live demo on stackblitz.