【问题标题】:How to create multi level menu using jade.pug如何使用jade.pug 创建多级菜单
【发布时间】:2016-08-17 02:06:41
【问题描述】:

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)

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)

问题:

编译成html时出现错误,在控制台显示:

Cannot read property of undefined in the "if menu.child.length > 0" row

编辑:

添加图片:

【问题讨论】:

  • 您的子菜单项没有 child 数组属性。将child: [] 添加到每个子项中,或者调整您的 if 语句以防止缺少该属性(即if menu.child && menu.child.length

标签: html css node.js pug


【解决方案1】:

当您调用+navbar(selected, menu.child) 时,问题在于menu.child 中的数据。 menu.child 中的对象没有child 属性,因此当 Pug 尝试获取此未定义值的长度时,会出现错误。

  1. 在数组menu.child的对象内添加child属性。
  2. 如果menu.child 不是未定义的,或者修改您的代码以更改(我假设您不想这样做,因为不会显示没有child 属性的对象:

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

【讨论】:

  • 谢谢@dzej.5。我用了你的第二个选项。它奏效了。
猜你喜欢
  • 2014-04-06
  • 1970-01-01
  • 1970-01-01
  • 2020-12-26
  • 2020-09-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多