问题
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