How to do nested iterations in jade?

巧了我就是萌 提交于 2020-01-14 05:36:09

问题


ul
    li
        a(href='') menu1
    li
        a(href='') menu2
        ul
            li
                a(href='') sub-menu2
    li
        a(href='') menu3
        ul
            li
                a(href='') sub-menu3
                ul
                    li
                        a(href='') secondary-submenu3

This is what I'm trying to achieve, instead of writing the above jade code I want to be able to generate it using loops. I tried the jade documentation, the examples show only one level of loop. For eg. I could try this

-var menus = [ 'menu1', 'menu2', 'menu3' ];
ul
    each menu in menus
        li
            a(href='') #{menu}

But this is not enough. if I try this

-var submenus = [ 'sub-menu1', 'sub-menu2', 'sub-menu3' ];
ul
    each menu in menus
        li
            a(href='') #{menu}
            ul
                each submenu in submenus
                li
                    a(href='') #{submenu}

this might work if each menu item had equal number of submenu items. But in my case number of submenu item differs for each menu item. How do i go around this? How to do nested iterations in jade?


回答1:


you need a object for this structure, for instance:

locals:

{
  menus: {
    m1: ['a', 'b', 'c', 'd'],
    m2: ['x', 'y', 'z'],
    m3: ['i', 'ii']
  }
}

then you can use this template:

ul
  each menuKey in Object.keys(menus)
    - menu = menus[menuKey]
    li
      a(href='')=menuKey
        ul
          each submenu in menu
            li
              a(href='') #{submenu}

you can try this on this site: http://jade-lang.com/demo/ copy paste the template to the top left, and the locals to the top right textarea.



来源:https://stackoverflow.com/questions/28615164/how-to-do-nested-iterations-in-jade

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