【问题标题】:Why the li tag not getting the value of loop variable?为什么 li 标签没有得到循环变量的值?
【发布时间】:2019-05-28 06:58:47
【问题描述】:

我正在尝试遍历来自 app.js 的对象。我在 PUG/JADE 中使用每个循环,以便我可以使用它的值来打印一些值。但是 li 没有得到循环变量的值

注意: 我得到 'post.title' 和 'post.body' 的次数低于 4 次,因为它来自 mongo 数据库,而我在数据库中正好做了 4 个条目。另外,这也意味着对象正确地进入了索引页面,但 li 没有获取循环变量的值。

我得到的输出

 . = post.title
 . = post.body
 . = post.title
 . = post.body
 . = post.title
 . = post.body
 . = post.title
 . = post.body

我想要什么

 Title of the post
 body of the post

 Title of another post
 Body of another post

 and so on....

我的代码

---- index.pug ----

block content
    ul
    each post in posts
        li = post.title
        li = post.body

---- app.js ----

let Post = require('./models/post');

app.get('/', function(req, res){
   Post.find({}, function(err, posts){

   if(err){
       console.log(err);
   } else {
      res.render('index', {   
        title:'Posts',
        posts: posts
     });
   }
 });
});

我还尝试了什么

我在循环上方创建了一个常量数组来检查和迭代该数组。但它给了我和

一样的结果
. = name
. = name
. = name

不知道为什么。代码如下。

block content
     - const names = ["Sami", "Abeer", "Hassaan"];
     ul.list-group
         each name in names
            li = name

【问题讨论】:

    标签: node.js express pug jade4j


    【解决方案1】:

    去掉li =之间的空格,得到li= name。空格表示等号应该是标签的内容。

    您的 index.pug 的完整示例:

    block content
        ul
        each post in posts
            li= post.title
            li= post.body
    

    【讨论】:

    • 谢谢,它运行良好。不知道为什么他们不允许在 = 符号之前留出空格。我的编程风格是在 = 符号前留出空格。
    • 不稳定。这只是一个哈巴狗的事情。所以你可以这样做: h1 我的超酷标题 这就是为什么 h1 =
    猜你喜欢
    • 2011-10-22
    • 2019-11-21
    • 1970-01-01
    • 1970-01-01
    • 2015-01-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-05-08
    相关资源
    最近更新 更多