问题描述
基于示例 here 我正在尝试使用 w3codecolor 进行 html 语法突出显示。
我添加了对 https://www.w3schools.com/w3css/4/w3.css
和 https://www.w3schools.com/lib/w3codecolor.js
的引用,然后调用 w3CodeColor();
函数
请注意,我的 html 具有我想按原样呈现的自定义元素。
HTML
<div class="w3-panel w3-card w3-light-grey">
<h4>Example</h4>
<div class="w3-code htmlHigh notranslate">
<file label="Please select a file." name="myimage" storage="{{bucket}}" validation="filetypes:.pdf|.txt|.xlsx maxfilesize:12345"></file>
<dropdown label="Can you select a single state?" name="state">
<option label="" value=""></option>
<option label="Oklahoma" value="OK"></option>
<option label="Texas" value="TX"></option>
<option label="New York" value="NY"></option>
</dropdown>
<input id="firstname" name="firstname" />
</div>
更新 1
根据建议,我使用 jQuery 转义了 html,它似乎正在工作。但是它不保留制表符缩进。关于如何保持标签缩进的任何建议?
//转义
$(".w3-code").each(function (i,v) {
var $code = $(v);
$code.text($code.html());
w3CodeColor();
});
解决方法
这是一个语法高亮。
它只是一个语法高亮。
它不会深入您的 HTML 源代码并将您嵌入的 XML 转换为您的 XML 的 HTML 表示。
如果您希望显示 &
字符,则需要对其进行转义 (&
)。 HTML 中的其他特殊字符也是如此。
一旦您编写了 HTML 以显示您想要的文本,语法高亮器就可以对其进行操作。
,因为你可以在 w3 的 see 中online demo(找到 here):
<div class="w3-panel w3-card w3-light-grey">
<h4>HTML Example</h4>
<div class="w3-code htmlHigh notranslate">
<!DOCTYPE html><br><html><br>
<title>HTML Tutorial</title><br>
<body><br><br>
<h1>This is a heading</h1><br>
<p>This is a paragraph.</p><br><br>
</body><br>
</html>
</div>
</div>
您需要转义这些特殊字符,@Quentin 解释得很好。
,添加 pre
标签有帮助
<div class="w3-panel w3-card w3-light-grey">
<h4>Example</h4>
<pre>
<div class="w3-code htmlHigh notranslate">
<file label="Please select a file." name="myimage" storage="{{bucket}}" validation="filetypes:.pdf|.txt|.xlsx maxfilesize:12345"></file>
<dropdown label="Can you select a single state?" name="state">
<option label="" value=""></option>
<option label="Oklahoma" value="OK"></option>
<option label="Texas" value="TX"></option>
<option label="New York" value="NY"></option>
</dropdown>
<input id="firstname" name="firstname" />
</div>
</pre>
</div>
JS
$(".w3-code").each(function (i,v) {
var $code = $(v);
$code.text($code.html());
w3CodeColor();
});