javascript - 如何使用jade和express在脚本标签中动态生成javascript

标签 javascript node.js express d3.js pug

我正在尝试为 d3 图动态生成 json 数据。我不确定这是否是最佳策略,但我的尝试本质上是在脚本标记中包含 d3 代码,然后通过 Express 中传递的对象生成 json。

我遇到的问题是我不确定如何在脚本标记中动态生成 json 数据。如果有更好的代码设计策略来动态生成 json 对象以传递给 d3 以使用 jade/pug 生成图表,请告诉我。下面的代码不起作用。

代码如下:

Jade 码

 //...content above, d3 to draw the graph below

        svg(height="800", width="1000").graph        
        script.
          var svg = d3.select("svg"),
          var data = #{dataObj}; // <--? how do I pass the json data object passed via route.js within the script tag?

...

route.js

let dataObj = {
  "nodes": [
    {"id": "Fantine", "group": 3},
    {"id": "Blacheville", "group": 3},
    {"id": "Favourite", "group": 3},
    {"id": "test", "group": 3},
    ],
    "links": [
    {"source": "Fantine", "target": "Blacheville", "value": 3},
    {"source": "Fantine", "target": "Favourite", "value": 4},
    {"source": "Fantine", "target": "test", "value": 4},
    ]
  };
    res.render('drawGraph', { dataObj});

控制台

Uncaught SyntaxError: Unexpected identifier
var data = [object Object];

预先感谢您的帮助!

最佳答案

就像 @Stretch0 提到的,你缺少对象的 key

res.render('drawGraph', { dataObj: dataObj});

但这并不能解决问题。您必须在 pug 模板中使用 JSON.stringify 来显示对象

来自

 var data = #{dataObj}; 

var data = !{JSON.stringify(dataObj)};

`#{} 转义字符,因此为了避免转义,您可以使用 !{}

关于javascript - 如何使用jade和express在脚本标签中动态生成javascript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44770476/

相关文章:

javascript - 如何使用 Mirth-Javascript 删除 HL7 消息中的换行符?

node.js - Node 等待 Promise.all() 完全解决

node.js - Express 和 Passport 之间的 Cookie 检测

javascript - 如何为具有一个分支和多个子项的数据集以不同颜色显示 d3 气泡?

javascript - 移动(Android)jquery onclick 设计

c++ - 无法安装 node-sass node.lib : fatal error LNK1107: invalid or corrupt file: cannot read at 0xB8790

node.js - 如何获取 Nodejs 中显示的 console.log 行号?

javascript - 使用 node.js 编辑和创建 HTML 内容

javascript - React 路由器和 Express GET 冲突

javascript - 在循环中等待嵌套的 Promise