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
?
#{variableName}
inside quotes, pug is evaluating that as a literal string. But when you are trying to use it outside any quotes, then it understands that this is a variable and uses its value instead. – Ingmar