在我的 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 href
,a(href='#{originalUrl}')
不起作用,而 a(href=originalUrl)
起作用。
但是,同一变量在“h2 Welcome to #{title}, #{count}, #{originalUrl}
”行正确计算为“Welcome to Login, 2,/login
”。
同一变量在 a href
和 h2
上的计算结果有何不同?
最佳答案
这是几个版本前(我认为是 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/