创建handlebars.js子菜单

时间:2015-06-30 11:52:17

标签: javascript jquery handlebars.js

我需要创建一个带把手的菜单,菜单中的一些选项有自己的子选项,我正在努力解决这个问题已经有1个小时了。

我的模板的JSON对象是

var menuJSON = [
{  
   name : "Schedule", 
   url: "index.html?lang=en", 
   icon: "fa fa-calendar-o",       
   state:"inactive"
},
{ 
  name : "Clients",  
  url: '#', 
  icon: "fa fa-users", 
  subs : ['Yours', 'Company'], 
  state:"inactive", subsTargetID: "collapse-menuC"
}
];

到目前为止,我的模板看起来像这样:

<div class="sidebarMenuWrapper" id="menuOpts">
    <script id="optsMenuTemp" type="x-handlebars-template">
        <ul class="list-unstyled">
        {{#each this}}
                <li class="{{state}}">
                    <a href="{{url}}"><i class="{{icon}}"></i>
                        <span>{{name}}</span>
                    </a>
                </li>
        {{/each}}
        </ul>
    </script>
</div>

这是子菜单选项的html:

<li class="hasSubmenu">
    <a href="#"  data-toggle="collapse" data-target="#collapse-menuD"><i class="fa fa-folder-open-o"></i>
        <span>{{documents.name}}</span>
    </a>
    <ul class="collapse" id="collapse-menuD">
        <li>
          <a href="index.html?lang=en&amp;top_style=inverse">
            <i class= "fa fa-street-view"></i>
            <span>{{documents.sub1}}</span>
          </a>
        </li>
        <li>
            <a href="index.html?lang=en&amp;top_style=default"><i class="fa fa-clipboard"></i>
                <span>{{documents.sub2}}</span
            </a>
        </li>
    </ul>
</li>

我无法正确使用if语句,而我现在真的需要一些帮助。

1 个答案:

答案 0 :(得分:1)

尝试以下代码

<ul class="list-unstyled">
{{#each this}}
        <li class="{{state}}"><a href="{{url}}"><i class="{{icon}}"></i><span>{{name}}</span></a>
        {{#if subs}}
          <ul class="collapse" id="collapse-menuD">
                   {{#each subs}}
                          <li><a href="index.html?lang=en&amp;top_style=inverse"><i class= "fa fa-street-view"></i><span>{{this}}</span></a>
                        </li>

{{/each}}
                    </ul>
        {{/if}}
        </li>
{{/each}}
</ul>

http://handlebarsjs.com/builtin_helpers.html