玉转换&和使用JavaScript时 [英] Jade converts & to & when JavaScript is used
问题描述
我刚开始使用 Harp 0.30.1 ,它随Jade一起安装预处理器.所以我也只是从Jade开始.
我有一个文件夹,其中包含一组文件名,例如This-is-an-MD-file.md
.在此文件夹中的index.jade
文件中,我想产生以下HTML输出:
<ul>
<li><a href="This-is-an-MD-file.html">This is an MD file</a></li>
</ul>
我对Jade和mixins有足够的了解,可以制作出这个...
- var trim = function(string) {
- var index = string.lastIndexOf(".")
- return string.substring(0, index).replace(/-/g, " ")
- }
mixin link(fileName)
li
a(href='#{fileName}') #{trim(fileName)}
ul
for file in public._contents
- if (file !== "index.html"){
+link(file)
-}
...这给了我我想要的东西.
但是,如果我尝试在替换功能中使用" "
而不是" "
,我会发现HTML输出使用&
而不是&
字符.
<li>
<a href="This-is-an-MD-file.html">
This&nbsp;is&nbsp;and&nbsp;MD&nbsp;file
</a>
</li>
那不是我想要的.
这仅发生在JavaScript函数中.如果我在普通的Jade标记部分中使用
,就像这样...
p non breaking space
... HTML的输出完全符合预期.
为什么会这样?有没有一种方法可以转义JavaScript部分中的&
字符,以便不将其转换为HTML实体?
您可以使用 Pug文档:
警告
请记住,如果未转义的内容来自用户,则将未转义的内容缓冲到模板中可能会带来巨大的风险.永远不要相信用户的输入!
I've just started using Harp 0.30.1 which comes with Jade installed as a pre-processor. So I'm just starting with Jade, too.
I have a folder containing a set of files with filenames like This-is-an-MD-file.md
. With the index.jade
file in this folder, I want to produce the following HTML output:
<ul>
<li><a href="This-is-an-MD-file.html">This is an MD file</a></li>
</ul>
I have understood enough about Jade and mixins to produce this...
- var trim = function(string) {
- var index = string.lastIndexOf(".")
- return string.substring(0, index).replace(/-/g, " ")
- }
mixin link(fileName)
li
a(href='#{fileName}') #{trim(fileName)}
ul
for file in public._contents
- if (file !== "index.html"){
+link(file)
-}
... which gives me what I want.
However, if I try to use " "
instead of " "
in the replace function, I see that the HTML output uses &
instead of the &
character.
<li>
<a href="This-is-an-MD-file.html">
This&nbsp;is&nbsp;and&nbsp;MD&nbsp;file
</a>
</li>
Which is not what I want.
This happens just in the JavaScript function. If I use
in the plain Jade markup section, like this...
p non breaking space
... the HTML is output exactly as expected.
Why is this happening? Is there a way to escape the &
character in the JavaScript section so that it is not converted to an HTML entity?
You can use the unescaped string interpolation syntax (!{variable}
) instead of the regular string interpolation syntax (#{variable}
) in order to get those non-breaking spaces to render.
In your case:
a(href= fileName) !{trim(fileName)}
But keep in mind this word of warning from the Pug documentation:
Caution
Keep in mind that buffering unescaped content into your templates can be mighty risky if that content comes fresh from your users. Never trust user input!
这篇关于玉转换&和使用JavaScript时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!