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

前端 未结 9 1013
逝去的感伤
逝去的感伤 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:13

    I solved this issue for myself by adding a short script tag to the bottom of my handlebars code!

    Add a class to wherever you are calling @index and then the below jQuery code works (can also be done using vanilla JS).

    <p class="create_index">
         {{@index}}
    </p>
    <script>
        $(".create_index").text(parseInt($(".create_index").text())+1)
    </script>
    

    edit 4/28- This has changed to use vanilla JS for better backwards compatibility (i.e. IE7, 8):

    <span class="create_index"></span>
    <script>
        var divs = document.querySelectorAll('.create_index');
        for (var i = 0; i < divs.length; ++i) {
            divs[i].innerHTML = i + 1;
        }
    </script>
    

    document.querySelectorAll has great compatibility but could also be document.getElementsByClassName("create_index")

    0 讨论(0)
  • 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}}
            <span>{{math @index "+" 1}}</span>
        {{/each}}
    
    0 讨论(0)
  • 2020-12-24 02:26

    To expand on Mobiletainment's answer, this solution allows for the value to be incremented by to be passed in as an argument. If no value is passed, then a default value of 1 is used.

    Handlebars.registerHelper('inc', function(number, options) {
        if(typeof(number) === 'undefined' || number === null)
            return null;
    
        // Increment by inc parameter if it exists or just by one
        return number + (options.hash.inc || 1);
    });
    

    Within your template you can then write:

    {{inc @index inc=2}}
    
    0 讨论(0)
提交回复
热议问题