如何在 < pre > 标记中转义 < 和 >

我正在尝试写一篇博客文章,其中包括一个代码段内的 <pre>标签。代码段包含一个泛型类型,并使用 <>定义该类型。这就是这个部分的样子:

<pre>
PrimeCalc calc = new PrimeCalc();
Func<int, int> del = calc.GetNextPrime;
</pre>

生成的 HTML 删除了 <>,结果如下:

PrimeCalc calc = new PrimeCalc();
Func del = calc.GetNextPrime;

如何转义 <>使它们显示在 HTML 中?

89452 次浏览

It's probably something specific to your blog software, but you might want to give the following strings a try (remove the underscore character): &_lt; &_gt;

How about:

&lt; and &gt;

Hope this helps?

&lt; and &gt; respectively

Use &lt; and &gt; to do < and > inside html.

<pre>&gt;</pre>

renders as:

>

So you want:

<pre>
PrimeCalc calc = new PrimeCalc();
Func&lt;int, int&gt; del = calc.GetNextPrime;
</pre>

which turns out like:

PrimeCalc calc = new PrimeCalc();
Func<int, int> del = calc.GetNextPrime;
<pre>
PrimeCalc calc = new PrimeCalc();
Func&lt;int, int&gt; del = calc.GetNextPrime;
</pre>

What rp said, just replace the greater-than(>) and less-than(<) symbols with their html entity equivalent. Here's an example:

<pre>
PrimeCalc calc = new PrimeCalc();
Func&lt;int, int&gt; del = calc.GetNextPrime;
</pre>

This should appear as (this time using exactly the same without the prepended spaces for markdown):

PrimeCalc calc = new PrimeCalc();
Func<int, int> del = calc.GetNextPrime;

A better way to do is not to have to worry about the character codes at all. Just wrap all your code inside the <pre> tags with the following

<pre>
${fn:escapeXml('
<!-- all your code -->
')};
</pre>

You'll need to have jQuery enabled for it to work, tho.