How to write code as an example, without executing?

17

I'm doing the translation of a book to an HTML page, there in the book have the codes, but how do I make my HTML display my code, HTML, PHP and JavaScript without running them?

    
asked by anonymous 24.04.2015 / 15:02

3 answers

15

You need to escape the characters that make your tags interpreted as HTML, < and > .

For example, instead of:

<div>Teste</div>

use:

&lt;div&gt;Teste&lt;/div&gt;

If you are using PHP, there is a function that does this, htmlentities :

echo htmlentities('<div>Teste</div>');

link

In the case of PHP code, simply output it without the <?php initial, and it will not be interpreted. If you want to include <?php in the example, use &lt;?php .

    
24.04.2015 / 15:05
11

You can use

<xmp>
  <p>Blah teste</p>
</xmp>

The xmp tag does not have to use escape characters.  The result will be:

<p>Blah teste</p>
    
24.04.2015 / 15:17
5

You can use the pre and jQuery tag:

jQuery(document).ready(function($) {
   $('pre').each(function(index, el){
     $(this).text( $(this).html() );
   });
});
pre{
  background-color: rgba(0,0,0,0.08);
  border-left: 3px solid rgba(0,0,0,0.4);
  margin: 0;
  padding: 4px 6px;
}

pre.php::before{
  content: '<?php';
  display:block;
  margin:0 0 2px -3px;
}
pre.php::after{
  content: '?>';
  display:block;
  margin:2px 0 0 -3px;
}

hr{margin 7px 0; border-color: #999;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script><pre><p>Testedatag<strong>pre</strong></p></pre><hr><preclass="php">
   $var = 'Hello World!';
   
   if (1 == 1)
     echo $var;
</pre>

But in the case of PHP, if you are also using it on the server side, you will have to omit the opening tag <?php (you can cast it by CSS).

    
24.04.2015 / 15:30