简体   繁体   English

在 pug 中将 JSON 作为 javascript 变量传递

[英]Pass JSON as javascript variable in pug

I want to pass an array of objects into my javascript code block but I am struggling because it would html encode the result so that I've got a lot of "我想将一组对象传递到我的 javascript 代码块中,但我很挣扎,因为它会对结果进行 html 编码,因此我有很多" in my actual JSON.在我的实际 JSON 中。

Basically my router gets the JSON object from the redis store and I am trying to pass it to the template:基本上我的路由器从 redis 存储中获取 JSON 对象,我试图将它传递给模板:

redis.getBuffer('languages', function (err, result) {
    res.render('manager/create-project', { title: 'Create Project', breadcrumbs: req.breadcrumbs(), languages: result })
})

I assign it like this to my variable:我像这样将它分配给我的变量:

script.
    $(document).ready(function() {
        var languages = #{languages};

The problem: The actual javascript variable languages gets the html encoded string as shown below.问题:实际的 javascript 变量语言获取 html 编码的字符串,如下所示。

var languages = [{"id":"aa","text":"Afar"}]

How can I properly pass my JSON content to the javascript block?如何将我的 JSON 内容正确传递给 javascript 块?

You need to interpolate without escaping.您需要在不转义的情况下进行插值。 This can be achieved by using !这可以通过使用来实现! instead of # .而不是#

For example, changing your template to the following should solve your issue:例如,将模板更改为以下内容应该可以解决您的问题:

script.
    $(document).ready(function() {
        var languages = !{languages};

For reference, here's the link to the docs作为参考,这里是文档的链接

The working way to do that is (I know is horrible but PUG works like this)这样做的工作方式是(我知道这很可怕,但 PUG 是这样工作的)

script(type="text/javascript").
    $(document).ready(function(){
       var languages = !{JSON.stringify(languages)}
    });

Working on 2018 2018年工作

More info on http://www.mircozeiss.com/how-to-pass-javascript-variables-from-a-server-to-angular有关http://www.mircozeiss.com/how-to-pass-javascript-variables-from-a-server-to-angular 的更多信息

This worked for me:这对我有用:

NodeJs :节点

res.render('itemdetails', {
    title: 'Donation item details',
    user: req.user,
    item: item.toJSON(),
    GOOGLE_MAP_API_KEY: process.env.GOOGLE_MAP_API_KEY
  });

Pug View :帕格视图

 script.
  $(document)
    .ready(() => {
    createGlobalObjects('minimap');
    let item = !{JSON.stringify(item)};
    initLocationSearch(positionItemOnMap.bind(item));
  });

Results:结果:

在此处输入图片说明

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

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