Tuesday, May 13, 2008

To show code snippets on Blogger

To get the <html> to appear like that on the browser, what I typed in to the actual HTML code is <html>. Confused? No it's not that difficult. This is what happens. When the browser reads an HTML document from beginning to end (yes, the browser also reads it as we do; technically this is called parsing) every < that it comes across will be replaced with the single character '<', before displaying the page for the human readers. Similarly, every HTML entity will be replaced with its corresponding display character.

What's the use of HTML entities anyway? Well, as I said before, one use is when we want to display code snippets in our page. Then there are some characters that we cannot type using the keyboard such as the '£' and the '€', which we can insert using HTML entities. Here's a full list of HTML entities from the W3Schools site.

A simple technique to replace entities
If you want to include a code snippet in one of your articles, you might have to replace many less-than and greater-than signs with the corresponding entities. This can be pretty cumbersome even for a few lines of code.

You can use a very basic text editor such as the Notepad (on Windows) to do it easily. Here's how.

1. Copy the code snippet in to a new Notepad document
2. Go to Edit -> Replace... (or Ctrl+H) and type '<' in the Find what box. Type '<' in the Replace With box.
3. Click Replace All
4. Repeat this for all the entities that you want to replace. (For example, '>' with '>' and '"' with '"')

No comments:

Post a Comment