[html] Display HTML snippets in HTML

How can I show HTML snippets on a webpage without needing to replace each < with &lt; and > with &gt;?

In other words, is there a tag for don't render HTML until you hit the closing tag?

This question is related to html tags

The answer is


I assume:

  • you want to write 100% valid HTML5
  • you want to place the code snippet (almost) literal in the HTML
    • especially < should not need escaping

All your options are in this tree:

  • with HTML syntax
    • there are five kinds of elements
    • those called "normal elements" (like <p>)
      • can't have a literal <
      • it would be considered the start of the next tag or comment
    • void elements
      • they have no content
      • you could put your HTML in a data attribute (but this is true for all elements)
      • that would need JavaScript to move the data elsewhere
      • in double-quoted attributes, " and &thing; need escaping: &quot; and &amp;thing; respectively
    • raw text elements
      • <script> and <style> only
      • they are never rendered visible
      • but embedding your text in Javascript might be feasable
      • Javascript allows for multi-line strings with backticks
      • it could then be inserted dynamically
      • a literal </script is not allowed anywhere in <script>
    • escapable raw text elements
      • <textarea> and <title> only
      • <textarea> is a good candidate to wrap code in
      • it is totally legal to write </html> in there
      • not legal is the substring </textarea for obvious reasons
        • escape this special case with &lt;/textarea or similar
      • &thing; needs escaping: &amp;thing;
    • foreign elements
      • elements from MathML and SVG namespaces
      • at least SVG allows embedding of HTML again...
      • and CDATA is allowed there, so it seems to have potential
  • with XML syntax

 

Note: > never needs escaping. Not even in normal elements.


You could try:

_x000D_
_x000D_
Hello! Here is some code:_x000D_
_x000D_
<xmp>_x000D_
<div id="hello">_x000D_
_x000D_
</div>_x000D_
</xmp>
_x000D_
_x000D_
_x000D_


The deprecated <xmp> tag essentially does that but is no longer part of the XHTML spec. It should still work though in all current browsers.

Here's another idea, a hack/parlor trick, you could put the code in a textarea like so:

<textarea disabled="true" style="border: none;background-color:white;">
    <p>test</p>
</textarea>

Putting angle brackets and code like this inside a text area is invalid HTML and will cause undefined behavior in different browsers. In Internet Explorer the HTML is interpreted, whereas Mozilla, Chrome and Safari leave it uninterpreted.

If you want it to be non-editable and look different then you could easily style it using CSS. The only issue would be that browsers will add that little drag handle in the bottom-right corner to resize the box. Or alternatively, try using an input tag instead.

The right way to inject code into your textarea is to use server side language like this PHP for example:

<textarea disabled="true" style="border: none;background-color:white;">
    <?php echo '<p>test</p>'; ?>
</textarea>

Then it bypasses the html interpreter and puts uninterpreted text into the textarea consistently across all browsers.

Other than that, the only way is really to escape the code yourself if static HTML or using server-side methods such as .NET's HtmlEncode() if using such technology.


This is a simple trick and I have tried it in Safari and Firefox

<code>
    <span><</span>meta property="og:title" content="A very fine cuisine" /><br>
    <span><</span>meta property="og:image" content="http://www.example.com/image.png" />
</code>

It will show like this:

enter image description here

You can see it live Here


This is how I did it:

$str = file_get_contents("my-code-file.php");
echo "<textarea disabled='true' style='border: none;background-color:white;'>";
echo $str;
echo "</textarea>";

i used <xmp> just like this : http://jsfiddle.net/barnameha/hF985/1/


In HTML? No.

In XML/XHTML? You could use a CDATA block.


<textarea ><?php echo htmlentities($page_html); ?></textarea>

works fine for me..

"keeping in mind Alexander's suggestion, here is why I think this is a good approach"

if we just try plain <textarea> it may not always work since there may be closing textarea tags which may wrongly close the parent tag and display rest of the HTML source on the parent document, which would look awkward.

using htmlentities converts all applicable characters such as < > to HTML entities which eliminates any possibility of leaks.

There maybe benefits or shortcomings to this approach or a better way of achieving the same results, if so please comment as I would love to learn from them :)


Kind of a naive method to display code will be including it in a textarea and add disabled attribute so its not editable.

<textarea disabled> code </textarea>

Hope that help someone looking for an easy way to get stuff done..


Deprecated, but works in FF3 and IE8.

<xmp>
   <b>bold</b><ul><li>list item</li></ul>
</xmp>

Recommended:

<pre><code>
    code here, escape it yourself.
</code></pre>

There are a few ways to escape everything in HTML, none of them nice.

Or you could put in an iframe that loads a plain old text file.


If your goal is to show a chunk of code that you're executing elsewhere on the same page, you can use textContent (it's pure-js and well supported: http://caniuse.com/#feat=textcontent)

<div id="myCode">
    <p>
        hello world
    </p>
</div>

<div id="loadHere"></div>


document.getElementById("myCode").textContent = document.getElementById("loadHere").innerHTML;

To get multi-line formatting in the result, you need to set css style "white-space: pre;" on the target div, and write the lines individually using "\r\n" at the end of each.

Here's a demo: https://jsfiddle.net/wphps3od/

This method has an advantage over using textarea: Code wont be reformatted as it would in a textarea. (Things like &nbsp; are removed entirely in a textarea)


It may not work in every situation, but placing code snippets inside of a textarea will display them as code.

You can style the textarea with CSS if you don't want it to look like an actual textarea.


It's vey simple .... Use this xmp code

    <xmp id="container">

&lt;xmp &gt;

    <p>a paragraph</p>

    &lt;/xmp &gt;

</xmp>

Ultimately the best (though annoying) answer is "escape the text".

There are however a lot of text editors -- or even stand-alone mini utilities -- that can do this automatically. So you never should have to escape it manually if you don't want to (Unless it's a mix of escaped and un-escaped code...)

Quick Google search shows me this one, for example: http://malektips.com/zzee-text-utility-html-escape-regular-expression.html


This is by far the best method for most situations:

<pre><code>
    code here, escape it yourself.
</code></pre>

I would have up voted the first person who suggested it but I don't have reputation. I felt compelled to say something though for the sake of people trying to find answers on the Internet.


The tried and true method for HTML:

  1. Replace the & character with &amp;
  2. Replace the < character with &lt;
  3. Replace the > character with &gt;
  4. Optionally surround your HTML sample with <pre> and/or <code> tags.

Actually there is a way to do this. It has limitation (one), but is 100% standard, not deprecated (like xmp), and works.

And it's trivial. Here it is:

<div id="mydoc-src" style="display: none;">
LlNnlljn77fggggkk77csJJK8bbJBKJBkjjjjbbbJJLJLLJo
<!--
YOUR CODE HERE.
    <script src="WidgetsLib/all.js"></script>
    ^^ This is a text, no side effects trying to load it.
-->
LlNnlljn77fggggkk77csJJK8bbJBKJBkjjjjbbbJJLJLLJo
</div>

Please let me explain. First of all, ordinary HTML comment does the job, to prevent whole block be interpreted. You can easily add in it any tags, all of them will be ignored. Ignored from interpretation, but still available via innerHTML! So what is left, is to get the contents, and filter the preceding and trailing comment tokens.

Except (remember - the limitation) you can't put there HTML comments inside, since (at least in my Chrome) nesting of them is not supported, and very first '-->' will end the show.

Well, it is a nasty little limitation, but in certain cases it's not a problem at all, if your text is free of HTML comments. And, it's easier to escape one construct, then a whole bunch of them.

Now, what is that weird LlNnlljn77fggggkk77csJJK8bbJBKJBkjjjjbbbJJLJLLJo string? It's a random string, like a hash, unlikely to be used in the block, and used for? Here's the context, why I have used it. In my case, I took the contents of one DIV, then processed it with Showdown markdown, and then the output assigned into another div. The idea was, to write markdown inline in the HTML file, and just open in a browser and it would transform on the load on-the-fly. So, in my case, <!-- became transformed to <p><!--</p>, the comment properly escaped. It worked, but polluted the screen. So, to easily remove it with regex, the random string was used. Here's the code:

    var converter = new showdown.Converter();
    converter.setOption('simplifiedAutoLink', true);
    converter.setOption('tables', true);
    converter.setOption('tasklists', true);
    var src = document.getElementById("mydoc-src");
    var res = document.getElementById("mydoc-res");
    res.innerHTML = converter.makeHtml(src.innerHTML)
            .replace(/<p>.{0,10}LlNnlljn77fggggkk77csJJK8bbJBKJBkjjjjbbbJJLJLLJo.{0,10}<\/p>/g, "");
    src.innerHTML = '';

And it works.

If somebody is interested, this article is written using this technique. Feel free to download, and look inside the HTML file.

It depends what you are using it for. Is it user input? Then use <textarea>, and escape everything. In my case, and probably it's your case too, I simply used comments, and it does the job.

If you don't use markdown, and just want to get it as is from a tag, then it's even simpler:

<div id="mydoc-src" style="display: none;">
<!--
YOUR CODE HERE.
    <script src="WidgetsLib/all.js"></script>
    ^^ This is a text, no side effects trying to load it.
-->
</div>

and JavaScript code to get it:

    var src = document.getElementById("mydoc-src");
    var YOUR_CODE = src.innerHTML.replace(/(<!--|-->)/g, "");

This is a bit of a hack, but we can use something like:

_x000D_
_x000D_
body script {_x000D_
    display: block;_x000D_
    font-family: monospace;_x000D_
    white-space: pre;_x000D_
}
_x000D_
<script type="text/html">_x000D_
<h1>Hello World</h1>_x000D_
_x000D_
<ul>_x000D_
    <li>Enjoy this dodgy hack,_x000D_
    <li>or don't!_x000D_
</ul>_x000D_
</script>
_x000D_
_x000D_
_x000D_

With that CSS, the browser will display scripts inside the body. It won’t attempt to execute this script, as it has an unknown type text/html. It’s not necessary to escape special characters inside a <script>, unless you want to include a closing </script> tag.

I’m using something like this to display executable JavaScript in the body of the page, for a sort of "literate progamming".

There’s some more info in this question When should tags be visible and why can they?.


You could use a server side language like PHP to insert raw text:

<?php
  $str = <<<EOD
  <html lang="en">
  <head>
    <meta charset="utf-8">
    <meta name="description" content="Minimal HTML5">
    <meta name="keywords" content="HTML5,Minimal">
    <title>This is the title</title>
    <link rel='stylesheet.css' href='style.css'>
  </head>
  <body>
  </body>
  </html>
  EOD;
?>

then dump out the value of $str htmlencoded:

<div style="white-space: pre">
  <?php echo htmlentities($str); ?>
</div>

function escapeHTML(string)
    { 
        var pre = document.createElement('pre');
        var text = document.createTextNode(string);
        pre.appendChild(text);
        return pre.innerHTML;
}//end escapeHTML

it will return the escaped Html


best way:

<xmp>
// your codes ..
</xmp>

old samples:

sample 1:

<pre>
  This text has
  been formatted using
  the HTML pre tag. The brower should
  display all white space
  as it was entered.
</pre>

sample 2:

<pre>
  <code>
    My pre-formatted code
    here.
  </code>
</pre>

sample 3: (If you are actually "quoting" a block of code, then the markup would be)

<blockquote>
  <pre>
    <code>
        My pre-formatted "quoted" code here.
    </code>
  </pre>
</blockquote>

nice CSS sample:

pre{
  font-family: Consolas, Menlo, Monaco, Lucida Console, Liberation Mono, DejaVu Sans Mono, Bitstream Vera Sans Mono, Courier New, monospace, serif;
  margin-bottom: 10px;
  overflow: auto;
  width: auto;
  padding: 5px;
  background-color: #eee;
  width: 650px!ie7;
  padding-bottom: 20px!ie7;
  max-height: 600px;
}

Syntax highlighting code (For pro work):

rainbows (very Perfect)

prettify

syntaxhighlighter

highlight

JSHighlighter


best links for you:

http://net.tutsplus.com/tutorials/html-css-techniques/quick-tip-how-to-add-syntax-highlighting-to-any-project/

https://github.com/balupton/jquery-syntaxhighlighter

http://bavotasan.com/2009/how-to-wrap-text-within-the-pre-tag-using-css/

http://alexgorbatchev.com/SyntaxHighlighter/

https://code.google.com/p/jquery-chili-js/

How to highlight source code in HTML?


 //To show xml tags in table columns you will have to encode the tags first

function htmlEncode(value) {
    //create a in-memory div, set it's inner text(which jQuery automatically encodes)
    //then grab the encoded contents back out.  The div never exists on the page.
    return $('<div/>').text(value).html();
}

html = htmlEncode(html)

A combination of a couple answers that work together here:

_x000D_
_x000D_
function c(s) {_x000D_
    return s.split("&lt;").join("<").split("&gt;").join(">").split("&amp;").join("&")_x000D_
}_x000D_
_x000D_
displayMe.innerHTML = ok.innerHTML;_x000D_
console.log(_x000D_
  c(ok.innerHTML)_x000D_
)
_x000D_
<textarea style="display:none" id="ok">_x000D_
<script>_x000D_
console.log("hello", 5&9);_x000D_
</script>_x000D_
</textarea>_x000D_
<div id="displayMe">_x000D_
_x000D_
</div>
_x000D_
_x000D_
_x000D_