views:

77

answers:

3

I want to some sample code in a html page. How do I do it, for example I want to show a tag and image tag, in stackoverflow I use 4 spaces:

A Tag example:
<a href="your_url"></a>

Image Tag example:
<img...>
+1  A: 

I think you're asking for the <pre> tag for preformatted text.

Everything that goes inside the pre tag it's not interpreted.

Try this on a browser:

<pre>
&lt;img src="whatever" /&gt;
&lt;othertag&gt;whatever&lt;/otherta&gt;
</pre>

EDIT: As Pekka pointed out, for HTML tags, symbols must be converted to their HTML entities.

Oscar Carballal
Not in my browser - I still get an interpreted image. Are you sure this is correct? IIRC, you need to make HTML entities out of the control characters in any case, `pre` or not.
Pekka
You're right, symbols must be converted to their respective HTML entities, sorry for the mistake.
Oscar Carballal
+2  A: 

To format the output, you can use the pre element.

Howver, you will still need to turn the special characters < > ' " & into their HTML entities &lt; &gt; and so on so the HTML tags turn up in clear text and don't get rendered by the browser.

If you can use PHP, there is htmlspecialchars() for that. Every server-side scripting language has an equivalent of it.

In JavaScript, setting the innerText property of the pre container leads to the characters being displayed literally and not as interpreted HTML.

If you want to do it manually, this is what you need to convert:

& to &amp;
> to &gt;
< to &lt;
" to &quot;
' to &#039

source

Pekka
A: 

You can use a combination of the <pre> and <code> tags. The <pre> tag formats everything inside of it as is appears in the source code (useful for showing large blocks of source), and the <code> tag is used for inline formatting of code (similar to how the tags in this answer are formatted). Also, anything inside the <code> tags need to be converted into HTML special characters (& gt; and & lt; for example).

tj111