layui本身是个非常棒的前段框架,自带的也有侧边栏功能,不过不 支持多级,子菜单也没有缩进,因此,我做了些调整。
树形菜单是通过Django的自定义标签渲染的。自定义标签代码如下:
def is_ancestor(current, menu):
"""
menu是否current的祖先
:param current: 当前菜单
:param menu:
:return: bool
"""
parent_id = current.parent_id
while parent_id != 0:
if parent_id == menu.unique_id:
return True
try:
parent_id = Menu.objects.get(pk=parent_id).parent_id
except Menu.DoesNotExist:
return False
return current.unique_id == menu.unique_id
@register.simple_tag(takes_context=True)
def side_bar(context):
root_menus = context["root_menus"]
current_menu = context["current_menu"]
request = context["request"]
html = '<ul class=" layui-nav layui-nav-tree">'
lists = []
for menu in root_menus:
# menu为根菜单,也就是一级菜单
menu = ObjectDict(menu)
# 确保右对齐,每个字的默认宽度为12px
arrow_distance = 120 - len(menu.name) * 12
url = menu.url or "javascript:;"
if url == request.path or is_ancestor