简体   繁体   English

使用express的nodejs应用程序中的JS文件中的EJS变量

[英]EJS variable in JS file in nodejs app using express

I have a user object having last_level property I am passing it in my express route as follows:我有一个具有last_level属性的user object 我在我的快速路由中传递它,如下所示:

app.get('/game', (req, res) => {
    res.render('main.ejs', { user: req.user })
})

I want to access it in my JS script file.我想在我的 JS 脚本文件中访问它。

After some research, I tried this...经过一番研究,我尝试了这个......

var x = <%- user.last_level %>  

But its not working (not giving me value of last_level to assign it to variale x).但它不起作用(没有给我 last_level 的值以将其分配给变量 x)。 Help me out on this please.请帮我解决这个问题。

This is my whole function -这是我的整个 function -

window.onload = function () {
    var x = <%- user.last_level %> 
    if (x === "Easy") {
        console.log("easy")
    } else if (x === "Hard") {
        console.log("hard")
    } else if (x === "Pro") {
        console.log("pro")
    }
    console.log(x)
};

Stringify your variable and see the results.对变量进行字符串化并查看结果。 Use the below code in your ejs template在您的 ejs 模板中使用以下代码

 <script>
    window.onload = function () {
            var x =  <%- JSON.stringify(user.last_level) %>
            if (x === "Easy") {
                console.log("easy")
            } else if (x === "Hard") {
                console.log("hard")
            } else if (x === "Pro") {
                console.log("pro")
            }
            console.log(x)
        };
    </script>

Alternative solution is替代解决方案是

 <script>
    window.onload = function () {
      <% if (user.last_level == 'Easy') { %>
        console.log("easy")
      <% } else if((user.last_level == 'Hard')  { %>
        console.log("hard")
      <% } else if(user.last_level == 'Pro')  { %>
        console.log("pro")
      <% } %>
    };
  </script>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM