Jade converts & to & when JavaScript is used

£可爱£侵袭症+ 提交于 2020-06-28 08:14:18

问题


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 "&nbsp;" instead of " " in the replace function, I see that the HTML output uses &amp; instead of the & character.

<li>
  <a href="This-is-an-MD-file.html">
    This&amp;nbsp;is&amp;nbsp;and&amp;nbsp;MD&amp;nbsp;file
  </a>
</li>

Which is not what I want.

This happens just in the JavaScript function. If I use &nbsp; in the plain Jade markup section, like this...

p non&nbsp;breaking&nbsp;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?


回答1:


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!



来源:https://stackoverflow.com/questions/57820158/jade-converts-to-amp-when-javascript-is-used

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!