node.js 如何在jade中渲染json对象并循环结果

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16301258/
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:22:02  来源:igfitidea点击:

how to render json object in jade and loop through results

javascriptjsonnode.jsexpresspug

提问by Brad.Smith

When I send a JSON string to a jade file for rending I'm only able to print out the string in it's entirety but not by it's elements. How do I print out specific elements or loop through the JSON string?

当我将一个 JSON 字符串发送到一个 jade 文件进行渲染时,我只能打印出整个字符串而不是它的元素。如何打印出特定元素或循环遍历 JSON 字符串?

app.js:

应用程序.js:

var http    = require('http'), 
    express = require('express'),
    net     = require('net');

var app = express();

app.set('views', __dirname + '/views');
app.set('view engine', 'jade');
app.use(express.logger('dev'));
app.use(express.static(__dirname + '/public'));

app.get('/', function (req, res) {
    var json_string = {"action":"date +%s","result":"1367263074"};
    res.render('index', { layout : 'layout', json: JSON.stringify(json_string) });
})
app.listen(3000);

layout.jade:

layout.jade:

!!!5
html
 head
  body
   p !{json}
   p !{json.result}
   p ---
    each val, key in json
     p #{key}: #{val}

expected output:

预期输出:

{"action":"date +%s","result":"1367263074"}
1367263074
---
action: date +%s
result: 1367263074

actual output:

实际输出:

{"action":"date +%s","result":"1367263074"}

---
0: {
1: "
2: a
3: c
4: t
5: i
6: o
7: n
8: "
9: :
10: "
11: d
12: a
13: t
14: e
15:
16: +
17: %
18: s
19: "
20: ,
21: "
22: r
23: e
24: s
25: u
26: l
27: t
28: "
29: :
30: "
31: 1
32: 3
33: 6
34: 7
35: 2
36: 6
37: 3
38: 0
39: 7
40: 4
41: "
42: }

回答by karaxuna

Why are you passing a string? Try this:

你为什么要传递一个字符串?尝试这个:

var ob = { action:"date +%s", result:"1367263074"};
res.render('index', { layout : 'layout', json: ob });

Or do this:

或者这样做:

-var ob = JSON.parse(json)
-for(var prop in ob)
 p #{prop}: #{ob[prop]}

回答by Mathieu Amiot

On this line : each val, key in jsonYou stringified your JS Object first (server-side), don't stringify it to get it as object.

在这一行:each val, key in json您首先将 JS 对象字符串化(服务器端),不要将其字符串化以将其作为对象。

So this line :

所以这一行:

res.render('index', { layout : 'layout', json: JSON.stringify(json_string) });

becomes

变成

res.render('index', { layout : 'layout', json: json_string });

回答by Bharat

If you are looking for looping over an array of actions and results, then use Mathieu Amiot's suggestion plus this code:

如果您正在寻找对一系列操作和结果的循环,请使用 Mathieu Amiot 的建议以及以下代码:

each key in json   
    p !{key.action} !{key.result}