Prism HTML highlighter

戏子无情 提交于 2019-11-30 00:50:23

问题


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.


回答1:


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>



回答2:


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.




回答3:


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>



回答4:


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.



来源:https://stackoverflow.com/questions/14559436/prism-html-highlighter

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!