简体   繁体   English

如何将对象从哈巴狗传递到前端javascript

[英]How to pass an object from pug to front end javascript

I´m using pug and I want to pass a variable to the front end for information, but when I´m trying to do that it pass like a text. 我正在使用帕格,我想将一个变量传递给前端以获取信息,但是当我尝试这样做时,它会像文本一样传递。

This is how I do that. 这就是我这样做的方式。

Controller code: 控制器代码:

res.render('view/edit', {
     title: 'Title',
     sub:true,
     data: variableObject
 });

This is the code in the rendered view: 这是渲染视图中的代码:

script(type='text/javascript').
    var x = "#{data}"
    console.log(x);

And this is the result of the log 这是日志的结果

[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]

I can´t access to the object because is text, is there a way to pass the object like an object? 我无法访问该对象因为是文本,有没有办法像对象一样传递对象?

First stringify your object using JSON.stringify : 首先使用JSON.stringify对对象进行字符串化:

res.render('view/edit', {
     title: 'Title',
     sub: true,
     data: JSON.stringify(variableObject)
 });

Then use String Interpolation, Unescaped !{data} 然后使用String Interpolation,Unescaped !{data}

script(type='text/javascript').
    var x = !{data}
    console.log(x);


Or just do it all once, in your template: 或者只是在模板中执行一次:

 script(type='text/javascript'). var x = !{JSON.stringify(data)} console.log(x); 

(kudos to @Matt, Thanks) (感谢@Matt,谢谢)

In this case I used this: 在这种情况下,我使用了这个:

var x = "#{ JSON.stringify(y) }"
   console.log( JSON.parse(x.replace(/"/g,'"')) );

I´m not sure if this is the best practice. 我不确定这是不是最好的做法。

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

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