Django variable in base.html

前端 未结 4 990
刺人心
刺人心 2020-11-30 04:35

base.html is used as the base template for all other pages. base.html has the navigation bar and in the navigation bar, I want to show the number o

4条回答
  •  天命终不由人
    2020-11-30 05:33

    I find the simplest steps to passing variables to your base templates in django is to add a context_processor.py file like so:

    In your app create context_processors.py and declare your variables e.g.:

    # context_processors.py
    def message_processor(request):
        if request.user.is_authenticated:
            no_msgs = request.user.profile.msgs
        else:
            no_msgs = 0
        return {
            'messages' : no_msgs
        }
    

    Then register your process or under TEMPLATES in your settings.py file:

    TEMPLATES = [
        {
            ...
                'context_processors': [
                    ...
                    # custom
                    'appname.context_processors.message_processor',
                ],
            },
        },
    ]
    

    And then you will be able to get that variable anywhere in your app as:

    {{ messages }}
    

提交回复
热议问题