HTML显示原始文本

3
我有一个HTML页面,需要显示一些日志信息。我将它们包裹在<pre></pre>中,但它似乎将日志消息解释为HTML,我希望它以原始方式打印出来。我尝试了"在HTML中显示纯文本,就像文本编辑器一样"或"防止<code>标签中的自动换行"或"如何使用CSS保留HTML中<code>块中的换行符?"等建议,但都不起作用(它们给出与我的原始HTML相同的结果)。
这是我的HTML页面:

code {
  font-size: 14px;
  display: block;
  font-family: monospace;
  white-space: pre;
  margin: 1em 0;
}
body {
  font-family: Arial;
}
<div>
  <h3>pre and code:</h3>
  <pre>
    <code>
[2016-06-24 16:06:00]|DEBUG|...., details='#<hashie::mash worker_address="http://xxx.amazonaws.com:8081" worker_id="0000000008" worker_task_id="776f31e01c530134025722000b27033c:gather_source_file_info_task_1466784360">'
    </code>
  </pre>
</div>

<div>
  <h3>only code:</h3>
  <code>
[2016-06-24 16:06:00]|DEBUG|...., details='#<hashie::mash worker_address="http://xxx.amazonaws.com:8081" worker_id="0000000008" worker_task_id="776f31e01c530134025722000b27033c:gather_source_file_info_task_1466784360">'
  </code>
</div>

<div>
  <h3>only pre:</h3>
  <pre>
[2016-06-24 16:06:00]|DEBUG|...., details='#<hashie::mash worker_address="http://xxx.amazonaws.com:8081" worker_id="0000000008" worker_task_id="776f31e01c530134025722000b27033c:gather_source_file_info_task_1466784360">'
  </pre>
</div>

以下是在浏览器上的渲染效果(使用的是最新版的Mac Chrome):

pre and code:



  [2016-06-24 16:06:00]|DEBUG|...., details='#'



only code:


  [2016-06-24 16:06:00]|DEBUG|...., details='#'

only pre:

  [2016-06-24 16:06:00]|DEBUG|...., details='#'

注意缺少的hashie::mash

我希望它打印出来的是:

  [2016-06-24 16:06:00]|DEBUG|...., details='#<hashie::mash worker_address="http://xxx.amazonaws.com:8081" worker_id="0000000008" worker_task_id="776f31e01c530134025722000b27033c:gather_source_file_info_task_1466784360">'

当日志包含一些XML时,我遇到类似的问题。


可能是在HTML中显示HTML代码的重复问题。 - Asons
4个回答

5
我知道的最简单的方法是:使用 `

1
我无法使其不换行(尝试了wrap="soft"overflow:scroll),但除此之外,这确实是最简单的解决方案。 - Kashyap
我更新了答案,不需要用css代码:white-space: nowrap;来包装。 - rafaelcastrocouto

3
你可以将希望显示原始格式的部分,用xmp标签包裹起来。
<xmp>[2016-06-24 16:06:00]|DEBUG|...., details='#<hashie::mash worker_address="http://xxx.amazonaws.com:8081" worker_id="0000000008" worker_task_id="776f31e01c530134025722000b27033c:gather_source_file_info_task_1466784360">'</xmp>

正如其他人所指出的,xmp已被弃用。这是一个更好的替代方案:

[2016-06-24 16:06:00]|DEBUG|...., details='#&lthashie::mash worker_address="http://xxx.amazonaws.com:8081" worker_id="0000000008" worker_task_id="776f31e01c530134025722000b27033c:gather_source_file_info_task_1466784360"&gt'

不必使用xmp标记进行包装,您可以用&lt替换“<”,用&gt替换“>”


2
"xmp"标签已被弃用,在某些浏览器中无法正常工作:https://developer.mozilla.org/en-US/docs/Web/HTML/Element/xmp - Asons
对于这个问题,我认为这可能是最好的答案,无论是否已被弃用,都是一个好的解决方案+1。 - Adam Buchanan Smith
1
<xmp> 元素可能已经被官方弃用,但是截至2019年9月,它在浏览器支持方面仍然“全面绿色”。它本来就是用于将HTML代码显示为文本的,因此对于临时内部/调试使用(而不是面向客户),它是完美选择。 - Daryn

1
抱歉我误解了问题。请将<hashie::替换为&#60hashie::

1

尝试用它们的HTML代码替换<>(标签)。例如:

<pre>some text</pre> change it to : &lt;pre&gt;sometext &lt;/pre&gt;

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接