2

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?

James Newton
  • 6,623
  • 8
  • 49
  • 113

1 Answers1

3

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!

Sean
  • 6,873
  • 4
  • 21
  • 46
  • 1
    I had seen the `!` but I hadn't tried putting it there. In this case, the input is the names of files on my development machine, so I'm the only user that I shouldn't be trusting. – James Newton Sep 06 '19 at 16:26