Tri Le Nguyen Huu Tri Le Nguyen Huu - 3 months ago 21
CSS Question

How to create multi level menu using jade.pug

In header.pug

block link
-var selected='Home';
-var menu = [{'title':'Home','address':'/home/home.html','child':[]},{'title':'Shopping','address':'/shopping/shopping.html','child':[{'title':'TV','address':'/tv/tv.html'},{'title':'Smartphone','address':'/smartphone/smartphone.html'}]},{'title':'About','address':'/about/about.html','child':[]}]

#navbar
+navbar(selected,menu)


In mixin.pug

//- Navbar mixin
mixin navbar(selected, menus)
ul
each menu in menus
if selected === menu.title
li.active
a(href=menu.address, title=menu.address)= menu.title
if menu.child.length > 0
+navbar(selected, menu.child)
else
li
a(href=menu.address, title=menu.address)= menu.title
if menu.child.length > 0
+navbar(selected, menu.child)


Problem:
When compile it into html, there is a error, shown in the console, Cannot read property of undefined in the "if menu.child.length > 0" row

Please help me to give your solution.

Thank you so much.

Ps: Add picture

[img]http://i.imgur.com/6QFtjSR.png[/img]

Answer

The problem is with the data in menu.child when you call +navbar(selected, menu.child). Objects in menu.child don't have a propety child, so when Pug try to get the length of this undefined values the error appears.

  1. Add child property inside objects in array menu.child.
  2. Or modify a little bit your code to change if menu.child is not undefined (I assume you don't want to, because objects without child property will not be displayed:

    if typeof menu.child == typeof []
        if menu.child.length > 0
            +navbar(selected, menu.child)