Adding offset to {{@index}} when looping through items in Handlebars

前端 未结 9 1028
逝去的感伤
逝去的感伤 2020-12-24 01:20

I\'m iterating over a list in Handlebars using the built-in each helper. Within the each block, I\'m referencing the current loop index

9条回答
  •  南笙
    南笙 (楼主)
    2020-12-24 02:15

    Actual answer: https://stackoverflow.com/a/46317662/1549191

    Register a math handlebar and perform all mathematical operations.

    app.engine('handlebars', exphbs({
      helpers:{
        // Function to do basic mathematical operation in handlebar
        math: function(lvalue, operator, rvalue) {lvalue = parseFloat(lvalue);
            rvalue = parseFloat(rvalue);
            return {
                "+": lvalue + rvalue,
                "-": lvalue - rvalue,
                "*": lvalue * rvalue,
                "/": lvalue / rvalue,
                "%": lvalue % rvalue
            }[operator];
        }
    }}));
    app.set('view engine', 'handlebars');
    

    Then you can directly perform operation in your view.

        {{#each myArray}}
            {{math @index "+" 1}}
        {{/each}}
    

提交回复
热议问题