Thursday, August 20, 2015

Display HTML code in another HTML page

I previously wrote about how <pre><code></code></pre> would help to output a code to a webpage. But what if you want to embed and display a html code? It's not so straight forward.

In blogger, I paste the code from my html file in the compose mode first. Then I go to the HTML mode and surround my html code with <pre> , <code> tags.

What this does is convert the special characters of html namely
< into &lt;
> into &gt;
& into &amp;

So it encodes the characters on the code and decodes them while displaying the page.
<pre> helps to keep the formatting (indentation, font, etc) the same as the setting in your text file or code editor file. <code> indicates to the web page that this is code.

This encoding decoding technique is useful when your client wants to display certain special characters, that interfere's with your code or overlaps with what are considered special characters by your code and cannot be used in your coding language.

This was one of my first UI exercises at my previous company. While it was a bank and many people complain that you don't get mainstream tech experience at such places, I say its the other way round. Getting to maintain legacy applications and old technology, you learn what you shouldn't be doing faster than if you wrote new code with latest technologies from scratch. My two cents - tech in banks is not so crazy or bad.

If you're building your own html page and want to embed some html code inside that page, copy the html code to embed into a notepad++ file and replace <, > and & with &lt; &gt; and &amp respectively. 

No comments:

Post a Comment