Show code snippet with syntax highlighting using prismjs inside webcomponent

623 views Asked by At

I am trying to show a code snippet using Prismjs for the syntax highlighting.

Some info about the project:

i am using lit-element and i have a code snippet saved as a string, which i want to show on the page with some nice syntax highlighting (using prismjs for this).

This is what the snippet looks like on the store (just a string):

snippet value in Store

Then inside a component i can render it as a string without problems, but i can't seem to get the syntax highlighting to work.

I am importing the styles and i also import prismjs at the top of the component like this: import Prism from 'prismjs';

To test, i am rendering the snippet in two different ways: the first one as it is saved on the store, and the second one by using the prism.highlight() function.

This is how they look like in the frontend:

Both ways it gets rendered in the frontend

and this is how i am rendering them in my component:

<pre>
   <code class="stage__code language-css">${this._selectedSnippet.code}</code>
   <code class="stage__code language-css">${this._highlightedCode}</code>
</pre>

The this._selectedSnippet.code gets the value as it is saved in the store.

The this._highlightedCode get the value from this getter:

get _highlightedCode() {
   return Prism.highlight(this._selectedSnippet.code, Prism.languages.css, 'css')
}

On the first one i see the correct snippet on the code block, but prism isn't highlighting it. On the second one i see that Prism added the classes it needs to highlight the code, but it is then rendered as a string (with the new markup added by prism).

Any ideas on how i can fix this? Thanks!

1

There are 1 answers

0
LuisBento On BEST ANSWER

Just moments after writing this question i remembered something, which allowed me to fix this problem.

I am writing it here, for the case someone else has the same problem.

lit-html has an unsafeHTML directive (here the documentation) which allows us to render as HTML instead of a string. Of course this should be used carefully, as it can lead to safety problems.

So i ended up importing this directive like this:

import { unsafeHTML } from 'lit-html/directives/unsafe-html';

and then rendering the code block like this:

<code class="stage__code language-css" id="codeContainer">
   ${unsafeHTML(this._highlightedCode)}
</code>