Explain Codes LogoExplain Codes Logo

How to escape < and > inside <pre> tags

html
html-entities
encoding
auto-escaping
Nikita BarsukovbyNikita Barsukov·Sep 5, 2024
TLDR

Encode < as &lt; and > as &gt; within <pre> tags to render angle brackets:

<pre>&lt;div&gt;Content&lt;/div&gt;</pre>

This renders as <div>Content</div> on the page.

Role of HTML entities in escaping

HTML entities like &lt; and &gt; are cornerstones in maintaining the structure and interpretation of your HTML code. They are text-based symbols that are universally recognized by browsers to represent a subset of characters, essentially ensuring your < and > symbols are interpreted as text instead of HTML tags.

Difference: Escaping vs. Encoding

Although similar, "escaping" and "encoding" have subtle differences:

  • Escaping means replacing a character with a special sequence, preventing it from being processed.
  • Encoding means transforming characters into different format or codes, making browsers display them as symbols instead of processing them as part of the HTML.

Auto-escaping with tools

To save time and decrease errors, various code editors and plugins exist that can auto-escape characters for you. For instance:

  • Sublime Text: Various plugins like HTML-CSS-JS Prettify for escaping.
  • Visual Studio Code: Has built-in features like Auto Rename Tag for managing and encoding.
  • IntelliJ IDEA: Provides a robust HTML and XML editor for auto-escaping.

Watch out for...

When escaping characters, be sure to avoid:

  • Inconsistency: Make sure both < and > are encoded, to prevent browser confusion.
  • Nested tags: Remember, when dealing with nested tags, encoding is necessary at each level.
  • Copy-pasting errors: When directly copying and pasting, verify that the entities are not decoded back to < and >.

The art of encoding and rendering

Getting our angle brackets to appear pixel-perfect is an art that requires precision. Displaying a snippet of code with unescaped < or > might cause your browser to misinterpret these symbols as an element, altering or even hiding your desired display.

<!-- If you dare to go without encoding --> <pre><div>Content</div></pre> <!-- Meh, the div tags might vanish! --> <!-- Safeguarding your divs with encoding --> <pre>&lt;div&gt;Content&lt;/div&gt;</pre> <!-- Voila, you see them divs right there -->

Conserving space and characters with <pre>

The <pre> tag acts like a magic wand, preserving both whitespace and line breaks, ensuring your code remains clean and human-readable despite the might of minifiers and parsers:

<pre> if (x &lt; y) { // Earth-shattering operations happening here } </pre>

Using &lt; within the if condition ensures our < symbol is protected - like a sacred relic - and displayed verbatim.