Search code examples
htmlhtml-encode

What do I need to escape inside the html <pre> tag


I use the <pre> tag in my blog to post code. I know I have to change < to &lt; and > to &gt;. Are any other characters I need to escape for correct html?


Solution

  • What happens if you use the <pre> tag to display HTML markup on your blog:

    <pre>Use a <span style="background: yellow;">span tag with style attribute</span> to hightlight words</pre>

    This will pass HTML validation, but does it produce the expected result? No. The correct way is:

    <pre>Use a &lt;span style=&quot;background: yellow;&quot;&gt;span tag with style attribute&lt;/span&gt; to hightlight words</pre>

    Another example: if you use the pre tag to display some other language code, the HTML encoding is still required:

    <pre>if (i && j) return;</pre>
    

    This might produce the expected result but does it pass HTML validation? No. The correct way is:

    <pre>if (i &amp;&amp; j) return;</pre>
    

    Long story short, HTML-encode the content of a pre tag just the way you do with other tags.