【问题标题】:How to display all entries in collection as html (node.js)如何将集合中的所有条目显示为 html (node.js)
【发布时间】:2016-07-03 17:41:24
【问题描述】:

我想将我的集合 (mongodb) 中的所有条目显示为 html。

我以前用基本的东西做过这个,例如......

router.get('/', function (req, res) {
    res.render('home', { title: 'Express', username: req.session.user, successful: req.query.valid });

});

我将usernamesuccessful 值用作html,以便在我的jade 文件中我可以像这样显示它们...

 body
   p #{successful}
   h1 
     |Welcome,
     span #{username}

但现在我想遍历 mongodb 中特定集合中的所有条目,并通过我的玉文件显示它们。我该怎么做?

【问题讨论】:

    标签: javascript node.js mongodb pug


    【解决方案1】:

    您可以在视图模板中使用迭代器来渲染集合中的所有元素。 为了获取该集合的所有元素,您需要在路由器内部定义一个查询(看看 mongoose)。 所以,你可以这样修改你的代码:

    var Model  = require('models/Model'); // this is your model schema
    
    router.get('/', function (req, res) {
        Model.find({}, function(err, result){
            if(err)
                return res.status(400).send(err);
            // here were are passing to our view all the elements we got from out query
            res.render('home', { title: 'Express', username: req.session.user, successful: req.query.valid, data: result });
        });
    });
    

    现在我们可以在翡翠模板中定义迭代器了:

     body
       p #{successful}
       h1 
         |Welcome,
         span #{username}
       ul
         for element in data
           li = element
    

    这里我假设你使用jade作为模板引擎,使用mongodb作为数据库,mongoose

    【讨论】:

    • 这行得通,我要注意,应该是li #{element}
    • 与“#{ }”和没有“#{}”的区别在于,第一种方法在渲染之前对内容进行评估和转义。看看这里的文档:jade-lang.com/reference/interpolation
    猜你喜欢
    • 2020-09-26
    • 1970-01-01
    • 2020-04-29
    • 2020-11-03
    • 1970-01-01
    • 1970-01-01
    • 2014-09-19
    • 1970-01-01
    • 2015-09-06
    相关资源
    最近更新 更多