Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/backbone.js/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Node.js 如何将阵列从Express server渲染到Pug并显示它_Node.js_Pug - Fatal编程技术网

Node.js 如何将阵列从Express server渲染到Pug并显示它

Node.js 如何将阵列从Express server渲染到Pug并显示它,node.js,pug,Node.js,Pug,需要向pug模板呈现一组用户,但该模板不起作用 哈巴狗 * * * each user in userList tr td= user.name td= user.address td= user.age * * * 服务器端代码 logger.Debug(JSON.stringify(data)); res.render('users.pug', { userList:JSON.stringify(data)}); 当我执行服务器端代码时,logg

需要向pug模板呈现一组用户,但该模板不起作用

哈巴狗

*
*
*
each user in userList
   tr
      td= user.name
      td= user.address
      td= user.age
*
*
*
服务器端代码

logger.Debug(JSON.stringify(data));
res.render('users.pug', { userList:JSON.stringify(data)});
当我执行服务器端代码时,logger.Debug()语句生成以下代码:

[{"name":"ABC","address":"London","age":"30"}, {"name":"DEG","address":"USA","age":"25"},
{"name":"XYZ","address":"India","age":"35"}]
但是,将相同的用户列表呈现给帕格是行不通的。它正在渲染空白


请任何人在此提供帮助和建议。

这是一个有效的版本

我改变了两件事:

  • 在模板中添加了
    元素(并删除了
    *
    ,我认为这是填充项)
  • 将实际对象传递给模板,而不是字符串
  • const pug=require('pug');
    让模板=`
    桌子
    userList中的每个用户
    tr
    td=user.name
    td=用户地址
    td=user.age
    `
    const compiledFunction=pug.compile(模板);
    让数据=[{“姓名”:“ABC”,“地址”:“伦敦”,“年龄”:“30”},{“姓名”:“DEG”,“地址”:“美国”,“年龄”:“25”},
    {“姓名”:“XYZ”,“地址”:“印度”,“年龄”:“35”}]
    设html=compiledFunction({
    用户列表:数据
    });
    document.getElementById('data')。innerHTML=html

    在服务器端,确保已将视图引擎定义为pug,并确保模板文件位于根级别的“视图”文件夹下

    例如:

    const express = require('express');
    const app = express();    
    app.set('view engine', 'pug');
    
    然后尝试一下,它应该会起作用

    注意:根据MarkMeyer注释,将表格添加到代码中,否则它不会在一行中打印每个tr。确保也有#{}用于动态变量替换

    block content
       table  
        each user in userList
          tr.person
            td #{user.name} 
            td #{user.age}
    

    不要把你的数据串起来!帕格需要看到的是数组,而不是字符串。我也试过了,但仍然无法在模板中查看
    *
    是否真的存在,或者它们是否代表其他删除的数据?非常感谢。我删除了json.stringfy()并直接传递了数组。成功了。再次谢谢你。事实上,我之前已经做过了,但它不起作用。现在,在再次移除它之后,它起了作用。可能是我没有重新启动服务器。那可能是我能想到的唯一的情况了谢谢Senthil。它在没有#{}的情况下也能工作。