node.jsexpresspugpugjs

Pug (formerly Jade) Variables Not Working (Interpolating) Correctly Inside Anchor Href


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.


Solution

  • 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')