0

In the Handlebars.js - template i am getting a senario to check the value of the array, and if the value is not equal to do a task and equal to do a taks.. i do like this, But it thrown a error, how to handle this scenario.. any one help me?

Or any one give the way to handle this properly.

myJson would be :

  {
        "links":[{"label":"x","link":"x"},
    {"label":"y","link":"y"},
    {"label":"Logout","link":"Logout"}]
 }


 {{#each links}}
                    {{#if !lable.Logout}}
                    <li>
                        <a href="{{link}}">{{label}}</a>
                        {{#if subLinks}}
                            <ul>
                                {{#each subLinks}}
                                    <li><a href="{{link}}">{{label}}</a></li>
                                {{/each}}
                            </ul>
{{else}}

<div><a href="{{link}}">{{label}}</a></div>


                    {{/if}}
            {{/each}}
4

1 回答 1

1

Handlebars alone cannot handle conditional if statements, you need to use a helper function.

<div id="myDiv"></div>

<script type="text/x-handlebars-template" id="handlebar">
{{#each links}}
    {{#ifCond label "Logout" }}
    <li>
        <a href="{{link}}">{{label}}</a>
        {{#if subLinks}}
            <ul>
                {{#each subLinks}}
                    <li><a href="{{link}}">{{label}}</a></li>
                {{/each}}
            </ul>
        {{/if}}
    {{else}}
        <div>
            <a href="{{link}}">{{label}}</a>
        </div>
    {{/ifCond}}
{{/each}}
</script>

<script>
    $( document ).ready(function() {
        var source   = $("#handlebar").html();
        var template = Handlebars.compile(source);
        var context =   {
            "links":[
                {"label":"x","link":"x"},
                {"label":"y","link":"y"},
                {"label":"Logout","link":"Logout"}
            ]
        };
        var html = template(context);
        $("#myDiv").html(html);
    });

    Handlebars.registerHelper('ifCond', function(v1, v2, options) {
      if(v1 === v2) {
        return options.fn(this);
      }
      return options.inverse(this);
    });
</script>
于 2013-07-15T14:06:24.710 回答