I have this C++ code (see my jsfiddle):
#include <ossource>
int main()
{
std::cout << "Hello World! n";
return 0;
}
I am trying to include that in a code section on my webpage with the indents etc intact, however when I place it in <pre>
tag (or similar) it doesn’t like the <ossource>
part because it believes the angled brackets <
and >
are html, not raw text. So it removes them (see jsfiddle above).
Is there an easy way to display this code exactly as it is?
I have tried using <code>
and <pre>
to no avail.
2
Answers
use HTML entities for
<
and>
charactersTo render language-reserved characters like
<
,>
, or, it’s common to escape the symbol, so that it won’t be interpreted as part of language syntax.
You could use
<
or<
for<
sign, and>
or>
for>
sign in HTML.See the sample snippet below.
Semantically, your content should be inside
<code>
within<pre>
, since it is pre-formatted code.This requires you to escape the reserved characters by using their respective HTML entities, as Bumhan Yu’s answer shows.
In case you do not want to properly escape the content and do not want to use semantically correct elements, you can use
<textarea>
.The
<textarea>
element only accepts text as its content, so any sequence except its own closing tag</textarea>
is allowed.Since
<textarea>
contains plain-text content, we should label its content type appropriately, by e.g. associating a<label>
element, or using thearia-label
attribute:Note: You may want to set the
readonly
boolean attribute to disallow editing. You can use thecols
androws
attributes to set the width and height in characters, respectively.