使用Handlebars的{{#each}}循环为表格行添加序号的方法
解决Handlebars循环中自动递增序号的问题
你可以通过两种方式实现自动递增的序号:
方法1:使用Handlebars自定义Helper
在你的Node.js项目中(比如app.js或路由文件)注册一个加法Helper,用来给循环索引加1(因为Handlebars的@index从0开始):
const hbs = require('hbs'); // 注册加法Helper hbs.registerHelper('add', function(a, b) { return a + b; });
然后修改你的.hbs模板,将固定的1替换为{{add @index 1}}:
<table class="table mt-5"> <thead> <tr> <th scope="col">No.</th> <th scope="col">Title</th> <th scope="col">Category</th> <th scope="col">Description</th> <th>Image</th> </tr> </thead> <tbody> {{#each products}} <tr> <th scope="row">{{add @index 1}}</th> <td>{{this.Name}}</td> <td>{{this.Category}}</td> <td>{{this.Description}}</td> <td><img style="width:100px" src="/product-images/{{this._id}}.png" alt="Img"></td> </tr> {{/each}} </tbody> </table>
方法2:在数据传递前添加序号字段
如果你不想自定义Helper,可以在从MongoDB获取数据后,给每个商品对象添加序号字段,再传递给模板:
// 示例路由代码 router.get('/products', async (req, res) => { // 从MongoDB查询商品列表 const products = await Product.find(); // 给每个商品添加从1开始的序号 const numberedProducts = products.map((product, index) => ({ ...product.toObject(), // 将Mongoose文档转为普通对象 serialNo: index + 1 })); // 传递带有序号的商品列表到模板 res.render('products', { products: numberedProducts }); });
然后修改模板中序号部分为{{this.serialNo}}:
<th scope="row">{{this.serialNo}}</th>
内容的提问来源于stack exchange,提问作者Sojo C Johny
相关产品推荐
相关产品推荐

