简体   繁体   English

如何在 pug 脚本中访问传递给 pug 的变量?

[英]How a passed variable to pug are accessible in pug script?

I am now to web development, in fact, this is the first one I am working on.我现在到web开发,其实这是我在做的第一个。 I am trying to pass a variable from my main app like我正在尝试从我的主应用程序中传递一个变量,例如

app.get('/',(req,res)=>{
    getdata().then(record=>{
        res.render("index",{title:'Login',users:record})
    })        
})

Then in my index.pug file the variable is accessible everywhere except my script there like然后在我的 index.pug 文件中,除了我的脚本之外,该变量在任何地方都可以访问

form()
          input(type="text", class='normal',id='uname', placeholder = 'Username')
          input(type="password", class='normal',id='password', placeholder='Password')
          input(type="submit", class='submit',value="Login",onclick="checkaccount(users)")
script.
    function checkaccount(users){
      let user=document.getElementById('uname').value
      let password = document.getElementById('password').value
      console.log(users)
    } 

the code won't execute because users variable is not defined I guess.代码不会执行,因为我猜未定义用户变量。 **users variable is an array of array with format array(a,b) this works when i use **users 变量是格式为 array(a,b) 的数组数组,这在我使用时有效

each val in users
    p.
        val

elsewhere from my scripts.我脚本的其他地方。

the script. script. means that everything that follows is interpreted as literal.意味着后面的所有内容都被解释为文字。 you can still use the code, but the syntax is different:您仍然可以使用代码,但语法不同:

script.
    var users = JSON.parse('#{JSON.stringify(users)'});
    function checkaccount(/*set users elsewhere*/){
      let user=document.getElementById('uname').value
      let password = document.getElementById('password').value
      console.log(users)
    } 

actually, this is not a good idea, better to use a serialization library, but the idea is that you have to serialize it, then tell put to get make a string literal '#{}' out of an expression #{} and then parse it on frontend ( JSON.parse('#{}') ).实际上,这不是一个好主意,最好使用序列化库,但想法是你必须序列化它,然后告诉 put 从表达式#{}中生成字符串文字'#{}'然后在前端解析它( JSON.parse('#{}') )。 You would have to JSON.stringify().replace(/'/g, "'") to prevent the single quote in one of your data to break this solution.您必须JSON.stringify().replace(/'/g, "'")以防止其中一个数据中的单引号破坏此解决方案。

on the frontend, with object {'hello': "world's"} :在前端,使用 object {'hello': "world's"}

- var myvalue = JSON.stringify(obj).replace(/'/g, "\\'");
JSON.parse('#{myvalue}')

becomes变成

JSON.parse('{"hello":"world\'s"}');

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

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