如何将Node.js变量传递到Pug脚本标签的内部? [英] How to pass a Node.js variable to the inside of a Pug script tag?

查看:128
本文介绍了如何将Node.js变量传递到Pug脚本标签的内部?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试获取一个已从Node.js发送到我的Pug页面的变量,并将其放在pug脚本标签内的javascript变量内. (抱歉,这很令人困惑)我的node.js代码如下:

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;

浏览器控制台将告诉我用户名未定义.如何在脚本标记内正确传递变量username的值?还有一种方法也可以将变量用户名传递到外部js文件中?预先感谢您的帮助!

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!

推荐答案

通常在哈巴狗中,您可以替换这样的变量,但是我们在

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.
      ^

为了在纯文本块中输出动态JavaScript,我们需要使用未转义的插值!{...}做到这一点.

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}';

当您有一个更复杂的JavaScript对象时,您可以对变量进行字符串化,并且由于它是有效的JavaScript输出,因此不需要引号.

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.

路线:

res.render('test', {
  user: {"name": "Joe Smith"}
});

模板:

var currentuser = !{JSON.stringify(user)};

输出:

<script>var currentuser = {"name":"Joe Smith"};</script>


如果您感到好奇,则#{...}转义的插值会插入无效字符,如下所示:


In case you're curious, the #{...} escaped interpolation inserts invalid characters and looks like this:

模板:

var currentuser = #{JSON.stringify(user)};

输出:

<script>var currentuser = {&quot;name&quot;:&quot;Joe Smith&quot;};</script>

这篇关于如何将Node.js变量传递到Pug脚本标签的内部?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆