How display source code in HTML page?
The are many ways of displaying raw source code in webpages. But we need a way which is supported by all browsers and all versions of HTML.
Tags like <xmp>, <plaintext> and <listing> and are deprecated. Displaying tags using those tags was the best way of displaying raw source code. But now we have other alternatives.
Now a days websites display source code using <pre>, <code> or <textarea>.
Let’s see how we can display source code using <textarea>
<textarea> preserves both spaces and line breaks. We don’t even have to escape html reserved character. To learn more about <textarea> tag tricks follow this link. The disadvantage of displaying code this way is that the code inside textarea cannot be highlighted.
Now let’s see how we can display source code using <pre> and <code> tags.
<pre> reserves both spaces and line breaks. <code> tag just provides proper font choice for displaying source code. But we have to escape html reserved characters for the code which we want to be displayed. This is the preferred way of displaying code in web pages.
Highlighting source code
Highlight can detect programming language automatically from our webpage. Highlight supports more than 70 programming language highlighting. They both have their merits and demerits.
We have to choose one among the two for our projects. So my personal favorite is Highlight.
Let’s see an example using Highlight:
In the above code hightlight.js automatically detects the programming language that is put inside <pre><code>..</code></pre>. The problem with the above code is that we still have to escape html reserved characters. We can have the code characters escaped server side which is better than escaping characters manually.
So we should use <pre> and <code> tags for displaying raw source code. And all code with HTML reserved characters should be escaped server side. You have the option to choose between Prism and Highlight libraries. Please Like and Share.