Google code-prettify Code highlighting not working for Polymer 3

599 Views Asked by At

How to use Google code-prettify in Polymer 3?

The syntax highlighting is not working. Sample code below:

class MyView1 extends PolymerElement {
    static get template() {
        return html` 
      <style include="shared-styles">

 </style>

       <script src="https://cdn.rawgit.com/google/code-prettify/master/loader/run_prettify.js"></script>

                <pre class="prettyprint">
                    <code class="language-java">
                        public static void getValue(){

                            String name = "Vikram";
                        }




                    </code>
                </pre>

I have added a working sample at https://stackblitz.com/edit/polymer-element-example-d7n14q where the code can be edited and run as well.

3

There are 3 best solutions below

3
On BEST ANSWER

This library is working in an old way and doesn't play well with ShadowDom. Instead you should use a library like Highlight.js which is available as a module. In polymer 3 first import the library with your specific language

import hljs from 'highlight.js/lib/highlight';
import java from 'highlight.js/lib/languages/java';
hljs.registerLanguage('java', java);

then highlight your element with

hljs.highlightBlock(this.$.code);

here a working example : https://stackblitz.com/edit/polymer-element-example-tthbbn

1
On

Did you add the style.css of prettify? https://cdn.rawgit.com/google/code-prettify/master/loader/prettify.css

Also I would try to put the language class in the pre class attribute. (also use lang instead of language)

If it colours it but don't as you expect you could try to send the lang as a get param: https://cdn.rawgit.com/google/code-prettify/master/loader/run_prettify.js?lang=java

3
On

It looks like you've got a solution using highlight, but to explain what's happening:

run_prettify.js prettifies everything in the DOM at onload time.

It doesn't recurse into shadow DOMs and doesn't prettify content that is added after onload.

You could address both issues by explicitly calling prettyPrintOne post render perhaps via Polymer.RenderStatus.afterNextRender though I don't know how that interacts with lithtml.