Displaying Raw HTML
If you’re here, you probably already know that the internet runs on HTML, amongst other languages. Browsers read and display pages written in it to your visitors. Displaying HTML on a website as itself, though? To show people the code? Kind of difficult, actually, and surprisingly so! On this site, though, I need to do it fairly often, since some of the content focuses on snippets of code itself, and other sites have similar purviews.
Regardless, a typical web browser (Firefox, Chrome, etc) coming across some HTML tends to sniff it a bit and immediately execute it. This is little fault of the browser, and is actually the most convenient and practical approach for most situations. Still, showing code on a page is sometimes important, and we need to find a way to do that. For me, the solution is to replace certain key elements (namely these symbols - < > and & ) with their extant character codes. This stops the browser from executing the HTML and thus allows it to display as HTML.
To do this, we’re replacing thusly:
- & becomes &
- > becomes >
- < becomes <
These modifications will prevent the HTML from actually being read by the browser as HTML - instead, the browser will think that this is just normal text. The final change (the line break thing) simply makes the HTML display as-is, ie as you entered it, preserving any ad hoc or intentional formatting you have given it within your editor. This is useful because most of us don’t have HTML files that are giant walls of code, and prefer things a little more organized. With the insertion of the line breaks, that stays.
The Input
The Output
The output below will not not not resemble anything like what you’ll see once this is copied and pasted into an HTML file. It’s going to look like ridiculous gibberish, let me tell you that. If you snag it, though, and past it into your HTML file wherever you’d like your code to be displayed, it should appear just as you entered it above, without executing within the browser, and displaying for visitors as code.