我正在尝试使用 Jade 呈现 SQL 查询的结果。它查询一个包含横幅的表,每个横幅都有一个类型(总共 3 个)和一个唯一的 id。
这是我拥有的:
表达:
connection.query("SELECT * FROM banner_idx ORDER BY id_type ASC, id_banner ASC", function selectCb(err, results, fields) {
if (err) {throw err;}
res.render('banners', {
title: results[0].title,
results: results
});
});
玉:
ul.listBanners
- each result in results
li.banner(data-type=result['id_type'])
- var item = result['id_banner']+': '+result['name_banner']
span=item
这为我提供了按所需顺序排列的横幅列表。现在我想以这种方式组织它(伪代码):
ul#id_type1
list of banners with id_type == 1
ul#id_type2
list of banners with id_type == 2
ul#id_type3
list of banners with id_type == 3
这可能与翡翠有关吗?我应该从 Express 发送 3 个结果集而不是 1 个结果集吗?那么问题就在于,任何新的id_type都需要硬编码......有什么想法吗?
您可以使用
lodash.groupBy
按id_type
对结果集进行分组:
var _ = require('lodash');
...
connection.query("SELECT * FROM banner_idx ORDER BY id_type ASC, id_banner ASC", function selectCb(err, results, fields) {
if (err) {throw err;}
res.render('banners', {
title : results[0].title,
groups : _.groupBy(results, 'id_type')
});
});
groupBy
返回一个如下所示的对象:
{
'1' : [
{ id_type : 1, ... },
{ id_type : 1, ... },
...
],
'2' : [
{ id_type : 2, ... },
{ id_type : 2, ... },
...
],
...
}
因此,该对象中的键是要分组的属性的值,在本例中id_type
。
您的模板将如下所示:
each entries, id in groups
ul(id = 'id_type' + id)
each entry in entries
li #{ entry.id_banner + ': ' + entry.name_banner }