【问题标题】:How do i put the sl. no. in table while using {{#each}} loop in handlebars我怎么把sl。不。在车把中使用 {{#each}} 循环时在表中
【发布时间】:2022-08-15 09:34:02
【问题描述】:

我正在创建一个表来显示数据库中的项目列表,但是在使用 {{#each}} 循环时如何为列表输入序列号:

 <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\">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>       

这是我正在使用的表格,在我写了 1 的 th 标签中,我想用 sl 替换它。不。这是一个 .hbs 文件,我使用 Node.js 和 MongoDB 作为数据库 我将如何做?

  • 什么是“sl. no.”?
  • 序列号 !或者我们可以说从 1 开始的索引号。
  • 我不明白,序列号是属于每个产品的属性,还是只是每一行的计数? - 1, 2, 3, ...
  • 是的,每一行的计数

标签: javascript html express-handlebars hbs


【解决方案1】:

Handlebars 提供了data-variable@index,用于在#each 迭代中获取当前项目的索引。但是,与 JavaScript 数组一样,@index0-based,因此您的结果将是 0, 1, 2, ... - 这不是您想要的。要使用@index,模板中受影响的行将变为:

<th scope="row">{{@index}}</th>

如果您需要序列号来启动1,则需要做更多的工作。 Handlebars 没有任何开箱即用的功能可以让我们将1 添加到@index。我们需要写一个custom helper,一个非常简单的。例如:

Handlebars.registerHelper('increment', function(num) {
    return num + 1;
});

然后我们的模板将变为:

<th scope="row">{{increment @index}}</th>

Here 是一个供参考的示例小提琴。

我对这种方法的感觉是,为了这样一个简单的目的添加一个助手是多余的。我建议为每个产品添加一个 SerialNumber 属性它在res.render() 调用之前传递给模板。它看起来像:

products.forEach((product, index) => {
  products[index].SerialNumber = index + 1;
});

这样,SerialNumber 将可用于您模板中的每个产品:

<th scope="row">{{this.SerialNumber}}</th>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-10
    • 2013-02-15
    • 1970-01-01
    • 2021-02-19
    • 2023-03-25
    相关资源
    最近更新 更多