【问题标题】:can't pass object to html with nunjucks无法使用 nunjucks 将对象传递给 html
【发布时间】:2016-11-06 22:43:52
【问题描述】:

我想使用 Nunjucks 将数据从 mongoDB 服务器传递到我的 html 文件以在加载时呈现。

App.js

app.get('/', function(req, res) {
    database.retrieveComments(req, function(err,result) {
        console.log(result);
        res.render('index.html', result);
    });
});

我的数据库连接文件在哪里:

connection.js

retrieveComments: function(req, callback) {
    db.collection('comments').find().toArray(function(err,result) {
        if (result.length > 0) {
            return callback(null, result);
        };
    });             
},

最后,在我的 HTML 文件中,我有这部分:

index.html

<div id="p" class="task" commentId = "1">
    1st comment {{ result }}
</div>

我可以在控制台登录时看到结果,但是当我浏览到本地服务器时,我似乎没有在 html 文件中呈现它。 如果我只是传递一个字符串,我可以看到它,但当我传递结果对象时却看不到。

我想知道这里是否有一些异步节点黑魔法在起作用,或者我是否缺少一些关键的 Nunjucks 元素。

【问题讨论】:

  • 使用res.render('index.html', {result: result});1st comment {{ result.smth-prop }}
  • 这些都不是。

标签: node.js template-engine nunjucks


【解决方案1】:
app.get('/', function(req, res) {
    database.retrieveComments(req,function(err, result) {
        if (err)
            return next(err); // Always check error
        console.log('DB result: ', result); // Verify that result is not empty
        res.render('index.html', {result: result});
    });
});

retrieveComments : function (req, callback) {
    db.collection('comments').find().toArray(function(err, result) {
        // callback must be called always
        if (err)
            return callback(err);

        if (result.length == 0) 
            return callback(new Error('Result is empty!')); 

        callback(null, result);
    });
}, 

<div id="p" class="task" commentId = "1">
1st comment {{ result }}
{{ result[0].name }} {# result is Array, right? #}
</div>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-11-16
    • 2011-09-20
    • 1970-01-01
    • 1970-01-01
    • 2014-10-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多