Interpolating values is helpful if you need to pass a server-side variable to client-side JavaScript (or other languages that require it).
In the case of variables, numbers, strings, and the like, you can pass these types of variables directly into your JavaScript with bracket syntax plus an explanation point (so that the code inside the brackets is not evaluated.) This is useful for parametrizing JavaScript code that require something from your server.
In the below example, we have to wrap username
in quotation marks in order for JavaScript to interpret it as a string; Pug will output the content of the variable as-is, so we need to put it in quotation marks for it to be a proper JavaScript string. This is not necessary for number
, where JavaScript will interpret our number as it we intend it to (as a number).
index.js
let number = 24;
let username = "John";
res.render("index", {
number: number,
username: username
});
index.pug
html
head
script.
// Sets the username of the current user to be displayed site-wide
function setUsername(username) {
// ...
}
var number = #{number};
var username = "#{username}";
setUsername(username);
body
p Welcome to my site!
index.pug output
<html>
<head>
<script>
// Sets the username of the current user to be displayed site-wide
function setUsername(username) {
// ...
}
var number = 24;
var username = "John";
setUsername(username);
</script>
</head>
<body>
<p>Welcome to my site!</p>
</body>
</html>
If you need to interpolate the value of a JavaScript object (e.g. all the information about a user), you must stringify the output in Pug for it to be treated as a JavaScript object. It's also necessary to output the raw contents of the variable, instead of the evaluated form of it. If you were to do output the escaped variable (var user = #{JSON.stringify(user)}
), you would receive an escaped version of the object (where quotation marks and apostrophes are converted to "
), which is not what we want in order for JSON.stringify
to work on it.
index.js
var myUser = {
name: "Leeroy Jenkins",
id: 1234567890,
address: "123 Wilson Way, New York NY, 10165"
};
res.render('index', {
user: myUser
});
index.pug
doctype html
html
head
script.
window.onload = function () {
function setUsername(username) {
return username;
}
var user = !{JSON.stringify(user)};
document.getElementById("welcome-user").innerHTML = setUsername(user.name);
};
body
div(id="welcome-user")
index.pug output
<!DOCTYPE html>
<html>
<head>
<script>
window.onload = function() {
function setUsername(username) {
return username;
}
var user = {
"name": "Leeroy Jenkins",
"id": 1234567890,
"address": "123 Wilson Way, New York NY, 10165"
};
document.getElementById("welcome-user").innerHTML = setUsername(user.name);
};
</script>
</head>
<body>
<div id="welcome-user"></div>
</body>
</html>
The innerHTML
of #welcome-user
becomes equal to Leeroy Jenkins
. The contents of the user
variable are printed directly to the HTML source