【问题标题】:Access objects globally in templates in Django 1.6在 Django 1.6 的模板中全局访问对象
【发布时间】:2014-04-21 13:18:15
【问题描述】:

我希望在 Django 1.6 中的所有页面上都有一个菜单。

在菜单中,我还想从我的数据库中包含一些对象。我知道我可以扩展 ListView 并获取对象,并且我知道我可以在get_context_data 中设置变量,但是我怎样才能使对象在我的所有页面上都可用。我认为在每个视图中设置 context_data 会很愚蠢。

我的菜单结果应该是这样的:

Home
Users
    User 1
    User 2
    User 3
Help
Questions
    Question 1
    Question 2
    Question 3
About

有什么好的方法吗?中间件?模板标签?

【问题讨论】:

    标签: django django-templates django-views


    【解决方案1】:

    您正在寻找自定义template context processor:

    你应该写一个这样的函数:

    #file: my_context_processors.py
    
    def menu_data(request):
    
        return {
                'menu': calculate_menu( request ),  #<-- menu is appended 
                                                    #    to your context
                                                    #    for all templates
                 }
    

    其中calculate_menu 返回一个带有菜单项和子项(字典?)的对象,比你有path、user 和其他信息到request。

    然后在应用设置模板上下文处理器中包含您的自定义处理器:

    TEMPLATE_CONTEXT_PROCESSORS = (
        "django.contrib.auth.context_processors.auth",
        "django.core.context_processors.debug",
        #"django.core.context_processors.i18n",
        "django.core.context_processors.media",
        "django.core.context_processors.static",
        "django.contrib.messages.context_processors.messages",
        "django.core.context_processors.csrf",
        'django.core.context_processors.request',
        'my_app.my_context_processors.menu_data',   #<---- here
        )
    

    此时,menu 对象可用于您的所有模板。

    不用担心条款,这并不难,这是正确的方法。

    【讨论】:

    • 谢谢!我可以在我的自定义上下文处理器中访问 url 参数吗?
    • 可以获取完整路径,但是不知道如何获取urls.py中指定的URL参数。
    • 寻找httpRequest结合ResolverMatch,即:HttpRequest.resolver_match。如果需要有关此主题的帮助,请发布新问题。
    猜你喜欢
    • 1970-01-01
    • 2011-06-05
    • 2021-01-06
    • 2012-12-28
    • 2012-07-02
    • 2011-12-17
    • 2017-02-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多