pug variable not evaluated on a href tag

*爱你&永不变心* 提交于 2020-12-29 18:55:55

问题


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?


回答1:


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}`)



回答2:


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



来源:https://stackoverflow.com/questions/51869135/pug-variable-not-evaluated-on-a-href-tag

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!