Normally in pug you can substitute variables like that, but we're in a Plain Text block when we put the period at the end of the script tag and regular variable substitution doesn't work in these blocks:
script.
^
In order to output dynamic JavaScript in a Plain Text block we need to use unescaped interpolation to do it with !{...}
.
If you are just trying to output a single string value just put quotes around the interpolation tag:
var currentuser = '!{username}';
When you have a more complex JavaScript object you can stringify the variable, and you won't need quotes for this as it's valid JavaScript output.
route:
res.render('test', {
user: {"name": "Joe Smith"}
});
template:
var currentuser = !{JSON.stringify(user)};
outputs:
<script>var currentuser = {"name":"Joe Smith"};</script>
In case you're curious, the #{...}
escaped interpolation inserts invalid characters and looks like this:
template:
var currentuser = #{JSON.stringify(user)};
outputs:
<script>var currentuser = {"name":"Joe Smith"};</script>
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…