Search code examples
javascriptpughtml-entitiesharp

Jade converts & to & when JavaScript is used


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?


Solution

  • 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!