@index not working in handlebars

你离开我真会死。 提交于 2019-12-07 13:00:09

问题


I am trying to use @index in handlebars as follows:

<script id="some-template" type="text/x-handlebars-template">
<form class = "pod" action="#" method="post">

<table>
<thead> 
    <th>Name</th> 
    <th>shipment</th> 
    <th>Button</th> 
</thead> 
<tbody> 
    {{#each objects}} 
    <tr> 
       <td>{{name}}</td> 
       <td> <input type="text" id="Shipment"  name={{join 'Shipment' name}}  /> </td>
   <td> <input type="submit" name="actionButton"  value = "update" >  </td>

  {{#if @index == 2 }}       
   <td> 
    <a href ="http://www.datatables.net/examples/api/select_single_row.html{{name}}">  {{name}} </a> 
   </td>

   <td> </td>
      {{/if}}   

 {{/each}} 
</tbody> 
</table> 
</form>
</script>

But my if condition does not seem to be working. Can anyone tell me what i am doing wrong?


回答1:


You can't do comparisons in Handlebars without a custom helper unfortunately.

I can't recall where I found this function, but I had a copy I was using in a node / express script to set the class based on a condition:

app.js

var hbs = require('hbs');

hbs.registerHelper('ifCond', function (v1, operator, v2, options) {
    switch (operator) {
        case '==':
            return (v1 == v2) ? options.fn(this) : options.inverse(this);
        case '===':
            return (v1 === v2) ? options.fn(this) : options.inverse(this);
        case '<':
            return (v1 < v2) ? options.fn(this) : options.inverse(this);
        case '<=':
            return (v1 <= v2) ? options.fn(this) : options.inverse(this);
        case '>':
            return (v1 > v2) ? options.fn(this) : options.inverse(this);
        case '>=':
            return (v1 >= v2) ? options.fn(this) : options.inverse(this);
        case '&&':
            return (v1 && v2) ? options.fn(this) : options.inverse(this);
        case '||':
            return (v1 || v2) ? options.fn(this) : options.inverse(this);
        default:
            return options.inverse(this);
    }
});

hbs template

<div class="{{#ifCond this.order.pushed '==' 'true'}}text-green{{/ifCond}}">Order Status - {{this.order.pushedMessage}}</div>


来源:https://stackoverflow.com/questions/27787914/index-not-working-in-handlebars

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!