Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
616 views
in Technique[技术] by (71.8m points)

javascript - How to pass a Node.js variable to the inside of a Pug script tag?

I am trying to take a variable I've sent to my Pug page from Node.js and place it inside a javascript variable inside of a pug script tag. (Sorry if that is confusing) My node.js code is as follows:

app.get('/profile', function (req, res) {
  var session = req.session;
  res.render('./login.pug', { username: session.uniqueID });
});

When I use the variable in my pug page code like this

input(type='text', id='username', value=username)

it works fine. The value will be changed to the username that the variable holds. But when I try to put the same value in my script tag such as

script.
        var currentuser = username;

the browser console will tell me that username is undefined. How do I properly pass the value of the variable username inside the script tag? Also is there a way to pass the variable username into an external js file as well? Thank you in advance for your help!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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 = {&quot;name&quot;:&quot;Joe Smith&quot;};</script>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...