简体   繁体   中英

Handlebars Helper Function

I am trying to return a value from the helper function in handlebars and display it Here is my code-

<div id="test"></div>
<script id="template" type="text/x-handlebars-template"> 
{{#each this}}

<hr/>


<div id="table">
    <table>
    <tr>
        <td>
            <div id="steps" style="color: #000000; font-size:36px;">{{steps}}</div><br></td>
        </td>
    </tr>


</table>
</div>
{{/each}}
</script>
<script
    src="http://cdnjs.cloudflare.com/ajax/libs/mustache.js/0.7.0/mustache.min.js"></script>
<script type="text/javascript"
    src="//ajax.aspnetcdn.com/ajax/jquery/jquery-1.9.0.min.js"></script>
<script
    src="https://cdnjs.cloudflare.com/ajax/libs/handlebars.js/2.0.0/handlebars.js"></script>
<script>
    $(document)
            .ready(
                    function() {

                        var source = $("#template").html();
                        var template = Handlebars.compile(source);

                        var rdata = [ {
                            "totalSteps" : 100,
                            "name" : "Dummy",
                            "heightFeet" : 5,
                            "averageSteps" : 10,
                        }, {
                            "totalSteps" : 10000,
                            "name" : "TestMan",
                            "heightFeet" : 4,
                            "averageSteps" : 10,
                        } ];
                        Handlebars.registerHelper('steps', function(rdata,index) {

                            var val=rdata[index].totalSteps;
                            return val.toLocaleString();
                        });

                        var ht = template(rdata);

                        $("#test").html(ht);
        });

</script>

But , I get this error

Uncaught TypeError: Cannot read property 'totalSteps' of undefined

Also , I tried to write the function like this -

$("#class").each function(index) {
return rdata[index].totalSteps;
});

But it does not display anything. Can anyone please help me fix this.

You need to pass the required data into the helper. Here is a simplified version.

{{#each rdata as |value index|}}
  {{steps ../rdata index}}
{{/each}} 

{ 
  rdata: [ {
    totalSteps: 100,
    name: "Dummy",
    heightFeet: 5,
    averageSteps : 10,
  }, {
    totalSteps : 10000,
    name: "TestMan",
    heightFeet: 4,
    averageSteps: 10,
  }]
}

Handlebars.registerHelper('steps', function(rdata,index) {
  var val=rdata[index].totalSteps;
  return val.toLocaleString();
});

The above example works in tryhandlebarsjs

I just did this

Handlebars.registerHelper('steps', function() {
                            return this.totalSteps;
});

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