简体   繁体   中英

pug variable not evaluated on a href tag

In my Express JS web app, a login route renders some variables to the login pug view.

In login.js

router.get('/login', function(req, res, next) {
  var locations = ["Location 1", "Location 2"];
  var count = 0;
  var title = 'Login';
  console.log("req.originalUrl=" + req.originalUrl);

  res.render('login', {
           title: title, // Give a title to our page
           jsonData: locations, // Pass data to the View
           count: locations.length,
           originalUrl: req.originalUrl
      });
});

In login.pug

extends layout

block content
  div(class='container mt-3')
    h2 Welcome to #{title}, #{count}, #{originalUrl}
    a(class="btn btn-primary" href="/location/new" role="button") NEW
    br
    br
    ul#locList(class='list-group')
      for location in jsonData
        li(class="list-group-item")
          a(href='#{originalUrl}' + '?' + location, class='list-group-item list-group-item-action')
            h2=location

The originalUrl variable in the a href was not evaluated as ' http://localhost:3000/login?Location%201 ', but ' http://localhost:3000/login#{originalUrl}?Location%201 ' instead.

Then I had to change it to ' a(href=originalUrl + '?' + location, class='list-group-item list-group-item-action') ' in order to make it work.

In a nutshell, a(href='#{originalUrl}') does not work while a(href=originalUrl) works, for a href .

However, the same variable was correctly evaluated at line ' h2 Welcome to #{title}, #{count}, #{originalUrl} ' as ' Welcome to Login, 2, /login '.

How was the same variable evaluated differently on a href from h2 ?

This is known behavior that came about a few versions ago (I think 2016). This #{style} interpolation is not supported in attributes:

Caution

Previous versions of Pug/Jade supported an interpolation syntax such as:

a(href="/#{url}") Link This syntax is no longer supported. Alternatives are found below. (Check our migration guide for more information on other incompatibilities between Pug v2 and previous versions.)

For more see: https://pugjs.org/language/attributes.html

You should be able to use regular template literals :

a(href=`${originalUrl}`)

There is an easy way to do that, write directly the variable, without using quotes, brackets, $, !, or #, like this:

a(href=originalUrl) !{originalURL}

The result of this is a link with the text in originalURL

Example: if originalUrl = 'www.google.es'

a(href='www.google.es') www.google.es

finally you get the link: www.google.es

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM