javascripthtmltypescriptlit-elementhighlight.js

Rendering an escaped string with lit element?


This demo first highlights html contained inside the fs-highlight element and assigns the result to the _code property.

The render method then renders the template with the _code highlighted html inserted into the code element like this:

  render() {
    if (this.language) {
      return html`
    <h1>Hello</h1>
    <pre><code class="language-${this.language}">${this._code}</code></pre>
    `;
    }
    return html`
    <h1>Hello</h1>
    <pre><code>${this._code}</code></pre>
    `;
  }

And I was expected to see <test></test>. However it renders as:

<span class="hljs-section">&lt;test&gt;</span><span class="hljs-section">&lt;/test&gt;</span>

And this is because the result has quotes around it like this (Looking at it in developer tooling):

"&lt;span class="hljs-section"&gt;&amp;lt;test&amp;gt;&lt;/span&gt;&lt;span class="hljs-section"&gt;&amp;lt;/test&amp;gt;&lt;/span&gt;"

How do we get it to render so that the browser converts the highlight string to html?


Solution

  • You can use the unsafeHTML directive which renders a string as HTML:

    import {unsafeHTML} from 'lit/directives/unsafe-html.js';
    ...
    <code>${unsafeHTML(this._code)}</code>
    

    Or you can use the browser's native innerHTML property:

    <code .innerHTML="${this._code}"></code>