Prism HTML highlighter

2019-02-12 00:08发布

I'm using Prism and its working well for CSS:

<pre><code class="language-css">p { color: red }</code></pre>

but i can't get it working for html:

<pre><code class="language-html"><p class="red">red text</p></code></pre>

I have 2 problems:

  1. < and > are represented as tags, not as text, but i could replace it by &lt; and &gt;

  2. More important, even replaced as shown in problem 1, the highliter will not highlight any code and everything is just black. Despite that it is working for CSS, whole code looks like this:

<!DOCTYPE html>
<html>
    <head>
        <link href="prism.css" rel="stylesheet" />
    </head>
    <body>
        <script src="prism.js"></script>
        <pre><code class="language-css">p { color: red }</code></pre>
    </body>
</html>

Thanks for any help.

4条回答
倾城 Initia
2楼-- · 2019-02-12 00:40

The best solution is to save the html you want highlighted into a seperate file. You'll need to include the file highlight plugin into your js.

The syntax highlighting will be worked out from the extension

<pre data-src="assets/partials/picture.html"></pre>
查看更多
戒情不戒烟
3楼-- · 2019-02-12 00:40

To solve issue 1):

You can use the unexcaped-markup plugin

This is how it works:

<script type="text/plain" class="language-markup">
   <p>Example</p>
</script>

To ignore first and last returns I would recommend using the normalize whitespace plugin.

To solve issue 2):

There exists no languages-html see http://prismjs.com/index.html#languages-list. HTML is a HyperTextMarkupLanguage so its included in language-markup. Thats what you have to use.

查看更多
我只想做你的唯一
4楼-- · 2019-02-12 00:42

I had the same problem with the HTML. I didn't want to replace the <, > with &lt &gt so what I did was put the code inside textarea-elements inside a hidden div and once the page was loaded copied the contents of all textareas to code-elements. This way I was able to keep the code as it is and render it withou issues.

The obvious downside of course is that without JS there is no content but then again the highlighter wouldn't work either.

查看更多
SAY GOODBYE
5楼-- · 2019-02-12 00:52

Use <code class="language-markup"> to style html code.

Also, you only need to escape the beginning of the tags with &lt;, don't worry about the &gt; characters. The easiest way is to paste your html code into the pre tag, then perform a find and replace for all < characters.

This should work:

<!DOCTYPE html>
<html>
    <head>
        <link href="prism.css" rel="stylesheet" />
    </head>
    <body>
        <script src="prism.js"></script>
        <pre><code class="language-markup">
            &lt;p class="red">red text &lt;/p>
        </code></pre>
    </body>
</html>
查看更多
登录 后发表回答