简体   繁体   中英

How do i put the serial number in each table row while using {{#each}} loop in handlebars?

I am creating a table to show list of items from the database, but how do I put the serial No. for the list when using an {{#each}} loop:

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

This is the table I am using. In the <th> tag I have written 1 . I want to replace it with the sl. no. This is an.hbs file and I am using Node.js and MongoDB as database.

How can I do it?

Handlebars provides a data-variable , @index , for getting the index of current item in an #each iteration. However, like JavaScript arrays, @index is 0-based , so your result would be 0, 1, 2, ... - which is not what you asked for. To use @index , the impacted line in your template would become:

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

If you require your serial numbers to start a 1 it will require a little more work. There is nothing out-of-the-box from Handlebars that will allow us to add 1 to @index . We would need to write a custom helper , a very simple one. For example:

helpers: {
  increment(num) {
    return num + 1;
  }
}

And then our template would become:

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

Here is an example fiddle for reference.

My feeling about this approach is that it is excessive to add a helper for such a simple purpose. I would recommend adding a SerialNumber property to each Product before it is passed to the template, before the res.render() call. It would look something like:

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

This way, the SerialNumber will be available to each Product in your template:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM