简体   繁体   中英

Google code-prettify Code highlighting not working for Polymer 3

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.

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

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM