Show user codes

2

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

I'd like to know how to do stylize code, just as it happens here in SOpt. Any code that I enter, it will apply colors, regardless of being php, html, javascript ....

Below is an image of my code viewer, currently:

HowIwouldlikeittobe:

My main questions are:

  • How to do this
  • Is there any ready-made library I can use?
  • Will this make the page load slower / more compromised?
asked by anonymous 26.08.2017 / 16:43

1 answer

2

This is called Syntax highlight and there are libraries that do this. You can do this on the server or on the client side, preferably asynchronously.

An example using the highlight.js library would be like this (with the 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><codeclass="language-js">
function teste() { 
    return 123;
}

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

Then you can define the core more or less to your liking.

    
26.08.2017 / 16:55