base.html中的Django变量 [英] Django variable in base.html

查看:327
本文介绍了base.html中的Django变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

base.html 用作所有其他页面的基本模板。 base.html 有导航栏,在导航栏中,我想显示用户收到的消息数。因此,我需要在 base.html 中的 {{number_of_messages}} 之类的变量。

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 of messages the user received. Thus, I need to have a variable like {{number_of_messages}} in the base.html.

然而,我该如何传递这个变量呢?每个模板都扩展了 base.html ,并由一个函数呈现。我不认为在所有功能中返回 number_of_messages 是一个很好的方法。有更好的方法来实现吗?如何将此变量传递给所有模板?

However, how should I pass this variable to it? Every template extends base.html and is rendered by a function. I don't think returning number_of_messages in all functions is a good way. Is there better way to implement this? How can I pass this variable to all templates?

推荐答案

看看:

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

只要:


  • 您在视图中使用 render 快捷方式(或以其他方式使用 RequestContext 来呈现您的响应)

  • TEMPLATE_CONTEXT_PROCESSORS 设置中有 django.contrib.auth.context_processors.auth 默认情况下为

  • 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)

...那么你有当前请求的用户(或 AnonymousUser )实例在您的模板中可用 {{user}} ...我从那里猜测可能是可以直接访问消息数量吗?

...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?

或者您正在使用Django的消息框架

Or perhaps you are using Django's messages framework?

这是自己的上下文处理器(只要你使用 render RequestContext )将使 {{messages}} var(包含当前用户)可用于您的模板。对于'邮件数量',您可以执行 {{messages | length}}

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)

制作自己的模板标签,只能在需要的地方使用...当然如果这是在你的 base.html ,所有模板都继承自 base.html ,那么它仍然会为每个页面运行。

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.

这篇关于base.html中的Django变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆