简体   繁体   中英

Parse markdown to HTML and highlight code syntax

I've downloaded a Markdown JS library but I don't know if it supports syntax highlighting, or any of his two supported dialects (gruber/maruku), because its the first time I try to add markdown support to my webpages. So, I would like to know how to integrate a syntax highlighter (like Alex Gorbatchev's JS library ) to markdown.

Any other libraries are welcome. Basically, my Markdown snippets are in .md files loaded that way:

<div class="markdown-f">
   <?= file_get_contents("file.md"); ?>
</div>

and it contains code snippets together with common Markdown text. I need a JS library to be able of doing something like:

<script>
   $('.markdown-f').each(function() {
        var contents = $(this).text();
        $(this).empty();
        contents = markdown.toHTML(contents);
        $(this).text(contents);
   });
</script>

with a dialect or any other hacktrick supporting syntax highlighting (specifying manually the target language for example).

I've used that markdown parser on my website to display the README files of repos I've created. It wraps code blocks in <pre><code> code goes here </code></pre>

It does not use highlighting, but you could then use the other library you mentioned after calling:

$("code").addClass("brush: js") // assuming you want to highlight javascript

Finally I used highlightjs .

The @A.OzanEkici solution has the (little) downside that I lost the markdown highglighting of my text editor (the emacs's markdown-mode ), since the contents inside the <pre> tag must be un-indent to don't see the indention in the rendered page, and the @JaredBeach doesn't work either because Alex Gorbatchev's library only work on <pre> tags, not on <pre><code> tags, which is what is replaced by the markdown syntax.

So, my solution was simply:

<script>
   $('.markdown-f').each(function(){
      $(this).html(markdown.toHTML($(this).text()));
   });

   hljs.initHighlightingOnLoad();
</script>

And that has the adventage that the language is automatically detected.

I use Alex Gorbatchev's JS library to do this and it works great.

First you should create a <pre> element like this;

<pre class="brush: __yourFileType__"> + data + </pre>

data refers to your contents and __yourFileType__ can be one of these .

Ex: class="brush: xml" , class="brush: txt"

After that you just simply call it;

SyntaxHighlighter.highlight();

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