如何在Node.js、MySQL与Handlebars环境下按国家分组统计姓名数量并通过#each命令展示
没问题!我来一步步给你拆解怎么实现这个需求,分后端数据处理和前端Handlebars模板渲染两部分来讲解:
第一步:后端(Node.js + MySQL)处理数据
首先你需要确保已经安装了所需的依赖包:
npm install mysql2 express express-handlebars
接下来写Node.js代码,负责连接MySQL、查询并整理数据,然后传给Handlebars模板:
const express = require('express'); const exphbs = require('express-handlebars'); const mysql = require('mysql2/promise'); const app = express(); // 配置Handlebars,注册一个判断相等的helper(用于处理单复数) const hbs = exphbs.create({ helpers: { eq: function(a, b) { return a === b; } } }); app.engine('handlebars', hbs.engine()); app.set('view engine', 'handlebars'); // 替换成你的MySQL配置 const dbConfig = { host: 'localhost', user: '你的数据库用户名', password: '你的数据库密码', database: '你的数据库名' }; app.get('/', async (req, res) => { try { // 建立数据库连接 const connection = await mysql.createConnection(dbConfig); // 核心查询:按国家分组,统计姓名数量并拼接所有姓名 const [rows] = await connection.execute(` SELECT country, COUNT(*) AS nameCount, GROUP_CONCAT(name SEPARATOR ', ') AS nameList FROM 你的数据表名 GROUP BY country ORDER BY country ASC `); await connection.end(); // 将整理好的数据传给模板 res.render('index', { countries: rows }); } catch (err) { console.error('数据库查询出错:', err); res.status(500).send('服务器内部错误'); } }); app.listen(3000, () => { console.log('服务器运行在 http://localhost:3000'); });
注意:记得把代码里的数据库配置、数据表名替换成你自己的实际信息。这里用GROUP BY country实现分组,COUNT(*)统计每个国家的姓名数量,GROUP_CONCAT把同一个国家的所有姓名拼接成逗号分隔的字符串,方便前端展示。
第二步:Handlebars模板渲染
在你的项目views目录下创建index.handlebars文件,编写模板代码:
<!DOCTYPE html> <html lang="zh-CN"> <head> <meta charset="UTF-8"> <title>按国家统计姓名</title> <style> .country-item { margin: 10px 0; padding: 8px; border-bottom: 1px solid #eee; } </style> </head> <body> <h1>按国家统计姓名</h1> <div class="country-container"> {{#each countries}} <div class="country-item"> <strong>{{country}}</strong>({{nameCount}} {{#if (eq nameCount 1)}}name{{else}}names{{/if}}): <span>{{nameList}}</span> </div> {{/each}} {{#unless countries}} <p>暂无数据可展示</p> {{/unless}} </div> </body> </html>
这里的核心逻辑是用{{#each countries}}遍历后端传过来的每个国家数据:
{{country}}显示国家名称{{nameCount}}显示统计的姓名数量- 通过
{{#if (eq nameCount 1)}}判断数量是1还是大于1,分别显示"name"或"names",实现你要的格式 {{nameList}}展示该国家的所有姓名
运行你的Node.js服务器后,访问http://localhost:3000就能看到按国家分组的姓名统计啦!
内容的提问来源于stack exchange,提问作者bahoz99
相关产品推荐
相关产品推荐

