我尝试使用res.render()传递的对象创建div。但是,有时会创建div,有时它们不会创建(如果我刷新页面)。我也使用Bootstrap。
JS /快递:
router.get('/', checkSignIn, function(req, res, next) {
db = new sqlite3.Database(file);
var tasks = {};
db.serialize(function () {
var query = "SELECT tasks.id, tasks.name, tasks.status FROM tasks JOIN users ON users.privilege = tasks.privilege WHERE users.id = '" + req.session.userid + "'";
db.all(query, function (err, rows) {
for(i = 0; i < rows.length; i++) {
tasks[i] = {
name: rows[i].name,
status: rows[i].status
};
console.log(tasks[i]);
}
});
});
db.close();
res.render('index', {
title: 'Home',
css: ['style.css', 'dist/wu-icons-style.css'],
username: req.session.username,
tasks: tasks
});
});
HBS:
<div class="container">
<div class="row">
<div class="col-md-6">
<div class="panel-group">
{{#each tasks}}
<div class="panel panel-primary">
<div class="panel-heading">
<h3 class="panel-title">{{name}}</h3></div>
<div class="panel-body">{{status}}</div>
</div>
{{/each}}
</div>
</div>
</div>
</div>
根据我添加的tasks
,每次都会正确填充console.log()
个对象。所以我认为问题在于Handlebars。
我在这里找到了一个解决方案:Handlebars not print {{this}} in each helper,但我没有使用this
。我尝试了./name
和./status
,但它没有帮助。有人可以帮助我吗?
答案 0 :(得分:1)
您的问题是异步javascript,而不是把手。您的tasks
对象正在填充,但您之前正在渲染html。如果您console.log(tasks)
位于db.close()
的当前位置之后,它将是一个空对象。您需要在数据库调用中移动render函数:
router.get('/', checkSignIn, function(req, res, next) {
db = new sqlite3.Database(file);
db.serialize(function () {
var query = "SELECT tasks.id, tasks.name, tasks.status FROM tasks JOIN users ON users.privilege = tasks.privilege WHERE users.id = '" + req.session.userid + "'";
db.all(query, function (err, rows) {
var tasks = {};
for(i = 0; i < rows.length; i++) {
tasks[i] = {
name: rows[i].name,
status: rows[i].status
};
console.log(tasks[i]);
}
res.render('index', {
title: 'Home',
css: ['style.css', 'dist/wu-icons-style.css'],
username: req.session.username,
tasks: tasks
});
});
});
db.close();
});