node.js 将数组传递给 Jade 渲染的 JSON 对象

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8293363/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 14:49:03  来源:igfitidea点击:

Passing an array to a JSON object for Jade rendering

node.jspug

提问by Masiar

I have a node.js server written in express and at a certain moment I send to some .jade page an array. The problem is that when rendering the Jade page, the Jade compiler renders the array as [object Object]and the JavaScript compiler on Chrome complains about it saying "Unexpected identifier".

我有一个用 express 编写的 node.js 服务器,在某个时刻我将一个数组发送到某个 .jade 页面。问题在于,在呈现 Jade 页面时,Jade 编译器将数组呈现为[object Object],而 Chrome 上的 JavaScript 编译器会抱怨它说“意外的标识符”。

This is the Jade code:

这是玉的代码:

!!! 5
html(lang="en")
    head
    title= "Rankings"

    body
        h1 Ranking

        div(id="rankings")

    script(type='text/javascript')

        function fillRanking(){
            var rankArray = #{ranking};
            alert("inside fillranking");
            var divElement = document.getElementById("rankings");
            for(var i = 0; i< rankArray.length; i++){
                divElements.innerHTML += "" + i+1 + ". " + rankArray[i].Username + " " + rankArray[i].Points;
            }
        }

        fillRanking();

As you can see it's really simple, I just fill a div with the info given by what's inside the #{ranking}variable passed by node.js to Jade. The alert on the second line doesn't fire because the Unexpected Identifier error happens as soon as I try to assign the #{ranking}variable.

正如你所看到的,这真的很简单,我只是#{ranking}用 node.js 传递给 Jade的变量中的内容提供的信息填充一个 div 。第二行的警报不会触发,因为一旦我尝试分配#{ranking}变量,就会发生意外标识符错误。

The following is the code in my node.js with express

以下是我的node.js中带有express的代码

app.get('/ranking', function (req, res) {
    //get the first ten people in the ranking
    var firstTen = getRanking(10, function(results){
        //compute the array of results
        var result = {
            ranking: [],
        }
        for(var i = 0; i < results.length; i++){
            result.ranking[i] = results[i];
        }
        //render the ranking with all the info
        console.log(result);
        res.render(__dirname + '/pages/ranking/ranking.jade', {
            ranking: result,
        });
    });
});

I create an object with inside an array of results, I put the results I found out of the query inside it and I pass it to the rendering engine. The console.log(results)call prints the resultobject correctly, for example like this:

我在结果数组中创建了一个对象,将查询中发现的结果放入其中,然后将其传递给渲染引擎。该console.log(results)调用result正确打印对象,例如:

{ ranking: 
   [ { Username: 'usr1',
       _id: 4ed27319c1d767f70e000002,
       Points: 100 },
     { Username: 'usr2',
       _id: 4ed27326c1d767f70e000003,
       Points: 100 } ] 
}

I don't really know how to handle the variable passed to the Jade page. Whichever thing I do I keep getting the "Unexpected identifier" error. Does anyone of you know how do I solve this?

我真的不知道如何处理传递给 Jade 页面的变量。无论我做什么,我都会收到“意外标识符”错误。你们中有人知道我该如何解决这个问题吗?

Thanks

谢谢

回答by luismreis

Looking at the comments above and investigating a little bit more, here's what I've found to work:

查看上面的评论并进行更多调查,这是我发现的工作:

Use this on your javascript (/controller):

在您的 javascript (/controller) 上使用它:

...
res.render(__dirname + '/pages/ranking/ranking.jade', {
    ranking: JSON.stringify(ranking),
})
...

And on jade template:

在玉模板上:

...
function fillRanking(){
  var rankArray = !{ranking};
  alert("inside fillranking");
...

This works because !{} doesn't perform escaping.

这是有效的,因为 !{} 不执行转义。

回答by Matt Kneiser

This works for me.

这对我有用。

JSON.stringifythe array (or any arbitrary JSON object really) on the server and then JSON.parseit on the client.

JSON.stringify服务器上的数组(或任何任意的 JSON 对象),然后JSON.parse它在客户端上。

server-side:

服务器端:

res.render(__dirname + '/pages/ranking/ranking.jade', {
    ranking: JSON.stringify(result),
});

client-side:

客户端:

var rankArray = JSON.parse( !{JSON.stringify(ranking)} );

回答by Razvan

Because I also use the array from the controller for iteration, I did this:

因为我也使用控制器中的数组进行迭代,所以我这样做了:

res.render('template', pArrayOfData);

And in the jade code:

在玉代码中:

script(type='text/javascript').
            var _histData = !{JSON.stringify(pArrayOfData)};

回答by ng-hacker-319

I encountered the same problem and was able make it work with a slight variation (thanks to the solutions above).

我遇到了同样的问题,并且能够通过轻微的变化让它工作(感谢上面的解决方案)。

From my code:
Backend:

从我的代码:
后端:

Stringify the JSON array

将 JSON 数组字符串化

router.get('/', function(req, res) {
    var data = JSON.stringify(apiData);  // <====
    res.render('gallery', { data: apiData });
}); 

Frontend:

前端:

Stringify again with the !{}

使用 !{} 再次字符串化

    function injectDataOnView() {

        var data = !{JSON.stringify(data)}; // <====
        var divElement = document.getElementById('data');
        divElement.innerHTML = data[1]['id']; // <=== just a test, so no for loop
    }

    injectDataOnView();