Escaping text in jade

So this question has been asked before, but I keep getting errors in my output.

So, escaping text in jade.

I have this markup

.left
  :markdown
  each post in site.posts
    a.post(href='#' + post.title)
      h2= post.title

The a tag will anchor scroll to the corresponding post. Now I want to escape that the post.title inside of the href so that the spaces are removed.

Now I’ve seen answers like this and this, but both of them throw errors when I try to compile everything.

The custom filter throws and error saying unknown filter and the second one throws this error

Unexpected token ILLEGAL
Potentially unhandled rejection [152] SyntaxError: /Users/mhartington/Github Repos/ionic-node-faq/views/index.jade:14
    12|       :markdown
    13|       each post in site.posts
  > 14|         a.post(href='#' + #{post.title})
    15|           h2= post.title
    16|     .right
    17|       each post in site.posts

Any ideas on what I’m doing wrong?

Answer

You can remove spaces from the post.title with .replace():

a.post(href='#' + post.title.replace(/s+/g, ''))

You may also use encodeURIComponent() to URL-encode other special characters for inclusion in URLs:

a.post(href='#' + encodeURIComponent(post.title.replace(/s+/g, '')))

The error with using #{...} is because it’s a Jade syntax that’s expected only within plain text. And, the values of attributes are parsed as JavaScript, which doesn’t support such syntax.

If you’re concerned about HTML-encoding the attribute’s value, Jade will already handle that as needed.

- post = { title: 'Foo>Bar' }
a(href='#' + post.title)
<a href="#Foo&gt;Bar"></a>

Leave a Reply

Your email address will not be published. Required fields are marked *