Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I insert code examples into an HTML file? [closed]

Tags:

html

I want to place an example of code without the tags being processed?

like image 897
Kevin Garcia Avatar asked Jan 16 '11 20:01

Kevin Garcia


People also ask

How do you add code to HTML file?

You can include code examples in your HTML by using the <code> tag. This automatically uses a monospaced font and also semantically labels our code as what it is.

How do I display code snippets in HTML?

The <code> tag is used to define a piece of computer code. The content inside is displayed in the browser's default monospace font. So, by using <pre> & <code>, you can display a code snippet such as function.

How do I edit HTML file?

By right-clicking on the HTML in the “Elements” tab and selecting “Edit as HTML,” you can make live edits to the markup of a webpage that Chrome will immediately render once you're done editing.


2 Answers

Xmp tag will work:

<xmp>    ...code... </xmp> 

ETA: As of this writing this still works in all major browsers, but as others have pointed out it has officially been obsoleted in HTML5 [link]. Browsers could stop rendering it any day without warning or notice and it should be avoided for production sites. Still, there is no replacement that doesn't involve HTML encoding your string manually or using iframe trickery. It still has a place in my personal utility page tool-belt, but I would not consider it for a client.

like image 123
Malk Avatar answered Sep 23 '22 01:09

Malk


The <pre> tag allows you to display text with whitespaces and line breaks as-is. Also, code must be entity-encoded: For example, the code sample

 <html>    <head><title></title></head>    <body></body>  </html> 

will become

<pre>&lt;html>   &lt;head>&lt;title>&lt;/title>&lt;/head>   &lt;body>&lt;/body> &lt;/html></pre> 

< encodes into &lt; & encodes into &amp;

PHP htmlentities does the job:

<pre><?php echo htmlentities($code) ?></pre> 

<textarea> does the job too: it also allow the code to be copied.

like image 40
Ming-Tang Avatar answered Sep 26 '22 01:09

Ming-Tang