Django variable in base.html

前端 未结 4 993
刺人心
刺人心 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:22

    Have a look at:
    https://docs.djangoproject.com/en/dev/ref/templates/api/#django.template.RequestContext

    As long as:

    • you use the render shortcut in your view (or otherwise take care to use a RequestContext to render your response)
    • have django.contrib.auth.context_processors.auth in your TEMPLATE_CONTEXT_PROCESSORS setting (as it is by default)

    ...then you have the current request's User (or AnonymousUser) instance available in your template as {{ user }} ...I am guessing from there you may be able to access the number of messages directly?

    Or perhaps you are using Django's messages framework?

    This comes with it's own context processor which (as long as you use render or RequestContext) will make a {{ messages }} var (containing the messages for current user) available in your templates. For 'number of messages' you can do {{ messages|length }}

    If none of these built-in options provide what you need you can either:

    • make your own template context processor which will run for every request and make additional variables available to all templates (when rendered with a RequestContext)

    • make your own template tag which can be used only where needed... of course if this is used in your base.html and all templates inherit from base.html then it's still going to run for every page.

提交回复
热议问题