16

I'm playing around with Node and Express and I'm using the Pug (formerly Jade) templating engine to render my html. Everything has been working fine up until I started trying to inject variables into the href of my anchor links. Whats odd is that if I change my Express app view engine to jade then things start working as expected.

Based upon other articles I've read the issue appears to be an interpolation issue, however I can't seem to find a resource or documentation that shows how to correctly fix this issue.

Ex.

I'm pulling in data from a rooms json array and then using a for loop to cycle through each array element and output the data for each room. Using jade the following works.

table.table.table-striped
  thead
    tr
      th Name
      th Id
  tbody
    each room in rooms
      tr
        td(style="width: 50px;")
          a(href!="/admin/rooms/delete/#{room.id}") Delete
        td #{allTitleCase(room.name)}
        td #{room.id}

Using pug the above does NOT work correctly. Specifically the a(href='/admin/rooms/delete/#{room.id}') Delete link doesn't work correctly. Instead of injecting the room id into the link href, it literally outputs #{room.id} as the end part the href link.

Any ideas how to fix this in pug?

Note that I've tried all of the following using pug but none of these options have worked.

  • a(href="/admin/rooms/delete/#{room.id}") Delete
  • a(href!="/admin/rooms/delete/#{room.id}") Delete
Corey
  • 481
  • 2
  • 5
  • 11

1 Answers1

26

UPDATE: Pug 2.0 introduced breaking changes to how interpolation is handled.

Based on the changelog, any of the following should work:

// to solve OP's problem, the following can be used:
a(href="/admin/rooms/delete/" + room.id) Delete

// Here are a few additional scenarios which use the new API 
// for anyone stumbling across this answer in the future
- var href = "/admin/rooms/delete/" + room.id;
a(href=href)
a(href=`${href}`) // Node.js/io.js ≥ 1.0.0
a(href=href + '?foo=bar')
pdoherty926
  • 9,895
  • 4
  • 37
  • 68
  • 1
    Thanks for the help, unfortunately this didn't work for me. While it did work on the jade-lang website, it doesn't appear to work in my Express app running `pug` as the `view engine`. I think it worked on the jade-lang website because that's actually using `jade` and not `pug`. – Corey Jul 18 '16 at 01:58
  • 2
    Have you read through [the Pug 2.0 changelog](https://github.com/pugjs/pug/issues/2305)? – pdoherty926 Jul 18 '16 at 02:03
  • After checking out the changelog like you suggested, I figured it out... I changed the anchor link to `a(href="/admin/rooms/delete/" + room.id) Delete` and this worked. Thanks for the help, I appreciate it. Can you edit your answer to include the correct code? If so I'll go ahead and mark your answer correct. – Corey Jul 18 '16 at 02:19
  • 1
    @Corey OK - updated. I left the additional examples for anyone else who runs into this issue in the future. – pdoherty926 Jul 18 '16 at 02:25