0

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?

1 Answer 1

1

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>
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.