我的django的网站将有3个独立的菜单。第一项是:联系,关于,披露。第二个将包括:条款和条件,隐私政策,版权。主菜单项有: Home、link1、link2、link2……前两个菜单将具有固定的项目,而最后一个菜单的项目可能会发生变化。由于我将在模板中使用forloop,那么创建这些菜单的最佳方法是什么?网页将只有一个标题和内容。
发布于 2011-05-31 09:43:11
我喜欢在动态菜单中使用inclusion template tags。
在my-app/templatetags/myappmenu.py中,我有类似这样的东西:
from django import template
register = template.Library()
@register.inclusion_tag('my-app/menu.html')
def myappmenu():
    return [("label1", "link1"), ("label2", "link2")]然后,在您的模板中,您可以循环遍历这些项,并以所需的格式(<p>、<ul>等)生成菜单。
如果需要有条件地显示菜单中的项目,可以通过检查模板标记中的权限将它们添加到列表中;只需将请求或用户对象作为参数传递给模板标记函数即可。
发布于 2015-08-31 04:01:05
你可以保持DRY,只使用。它还支持嵌套菜单。
安装:
pip install django-menuware
# Add `menuware` to your settings.py**
# Add `MENUWARE_MENU` to your settings.py:**设置:
MENUWARE_MENU = {
    "RIGHT_NAV_MENU": [
        {   # Show `Login` to `unauthenticated` users ONLY
            "name": "Login",
            "url": "/login/",
            "render_for_unauthenticated": True,
        },
        {   # Show `Logout` to `authenticated` users ONLY
            "name": "Logout",
            "url": "/logout/",
            "render_for_authenticated": True,
        },
        {   # Show `Search` to all users
            "name": "Search",
            "url": "/search/",
            "render_for_unauthenticated": True,
            "render_for_authenticated": True,
        },
    ],
    "LEFT_NAV_MENU": [
        {   # Show `Admin` to `superuser` ONLY
            "name": "Admin",
            "url": "admin:index", # Reversible
            "render_for_authenticated": True,
            "render_for_superuser": True,
        },
       {   # Show `Comment Admin` to `staff` users ONLY
            "name": "Comment Admin",
            "url": "/review/admin/",
            "render_for_authenticated": True,
            "render_for_staff": True,
        },
    ]使用:
<!-- base.html -->
{% load menuware %}
<!DOCTYPE html>
<html>
    <head><title>Django Menuware</title></head>
    <body>
        <!-- NAV BAR Start -->
        {% get_menu "LEFT_NAV_MENU" as left_menu %}
        <div style="float:left;">
            {% for item in left_menu %}
                <li class="{% if item.selected %} active {% endif %}">
                    <a href="{{item.url}}">{{item.name}}</a>
                </li>
            {% endfor %}
        </div>
        {% get_menu "RIGHT_NAV_MENU" as right_menu %}
        <div style="float:right;">
            {% for item in right_menu %}
                <li class="{% if item.selected %} active {% endif %}">
                    <a href="{{item.url}}">{{item.name}}</a>
                </li>
            {% endfor %}
        </div>
        <!-- NAV BAR End -->
    </body>
</html>至少,在推出自己的Github之前,你应该先看看它的Github README页面。
https://stackoverflow.com/questions/6182120
复制相似问题