javascript - pug 变量未在 href 标签上求值

标签 javascript node.js express pug

在我的 Express JS Web 应用程序中,登录 路由将一些变量渲染到登录 pug View 。

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

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

a href 中的 originalUrl 变量未计算为“http://localhost:3000/login?Location%201”,而是计算为“http://localhost:3000/login#{originalUrl}?Location%201”。

然后我必须将其更改为“a(href=originalUrl + '?' + location, class='list-group-item list-group-item-action')”才能使其正常工作。

简而言之,对于 a hrefa(href='#{originalUrl}') 不起作用,而 a(href=originalUrl) 起作用。

但是,同一变量在“h2 Welcome to #{title}, #{count}, #{originalUrl}”行正确计算为“Welcome to Login, 2,/login”。

同一变量在 a hrefh2 上的计算结果有何不同?

最佳答案

这是几个版本前(我认为是 2016 年)出现的已知行为。属性不支持此#{style}插值:

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.)

更多信息请参见:https://pugjs.org/language/attributes.html

您应该能够使用常规 template literals :

a(href=`${originalUrl}`)

关于javascript - pug 变量未在 href 标签上求值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51869135/

相关文章:

javascript - ng-click 与 Bootstrap 评级

arrays - 将数组元素从一个数组位置移动到另一个数组位置 (mongo)

javascript - 验证错误mongodb,node.js和Express后端

javascript - 基于数据对象的 Firebase 用户写入/读取规则

javascript - 如何动态拆分数组?

javascript - 创建一个 Restful API 端点,以便我可以将我的 Angular 8 应用程序连接到它

node.js - 如何在 Node.js 中创建僵尸/失效进程?

node.js - vorpal .validate 抛出错误

javascript - 将 POST react 到 Node 服务器并处理 JSON 响应

node.js - npm cors 包不工作