Show codes for user

Asked

Viewed 247 times

3

Hello! I have one forum and, in publications of my users, they can add codes to display them using the bbcode tag [code][/code].

I’d like to know how to make stylize the code, as it happens here in Sopt. Example: Any code I insert, it will apply colors, regardless of being php, html, javascript....

Below is an image of my code display currently: inserir a descrição da imagem aqui

How I wish it were:

inserir a descrição da imagem aqui


My main questions are:

  • How to do this
  • Is there any library ready that I can use?
  • This will slow/compromise page loading?

1 answer

3


That’s called Syntax Highlight and there are libraries that do that. You can do that on the server or client side, preferably asynchronously.

An example, using the library Highlight.js would look like this (with code inside tags pre and code):

<link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/highlight.js/9.12.0/styles/default.min.css">
<script src="//cdnjs.cloudflare.com/ajax/libs/highlight.js/9.12.0/highlight.min.js"></script>
<script>
    hljs.initHighlightingOnLoad();

</script>

<pre><code>
function teste() { 
    return 123;
}

var nr = teste();
console.log(nr);
</code></pre>

Another example with Prism.js

<link href="https://cdnjs.cloudflare.com/ajax/libs/prism/1.6.0/themes/prism.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/prism/1.6.0/prism.js"></script>

<pre><code class="language-js">
function teste() { 
    return 123;
}

var nr = teste();
console.log(nr);
</code></pre>

Then you can sort out the core to your liking.

  • 1

    Once again you answering exactly what I wished for. Thank you very much for the reply and congratulations on the good performance!

  • 1

    @VME great that I could help!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.