模板标签中的对象计数
Object count in template tags
我创建了一个自定义的简单标签来计算一个对象并 returns 它。我希望计数显示在导航栏内。因此可以通知用户。
- 我做了一个模板标签并注册了
- 我在 base.html
中加载了标签
- 我在导航栏中使用了标签,因为我希望在那里显示计数。
- 它只过滤字段 "live" 为 false
的对象
- 我在应用程序目录中创建了一个 templatetags 目录。
- 我在 templatetags
里面添加了一个 __ init __.py
notifications.py (templatetags/notifications.py)
from django import template
from home.models import ReportRequests
register = template.Library()
@register.simple_tag
def new_notification(request):
a = ReportRequests.objects.filter(live=False).count()
return a
base.html
{% load notifications %}
<a href="{% url 'home:report_request' %}"><i class="fas fa-inbox"></i><p>Requests</p><span class="badge badge-pill badge-danger">{{ new_notification }}</span></a>
我希望计数会显示在文本旁边,在带有 bootstrap 的徽章内。但是它没有显示任何内容。
您的代码中几乎没有简单的错误。
现在,只需按照以下步骤解决此问题。
在base.html.
中将{{ new_notification }}
替换为{% new_notification %}
Note: {{ template_context_variable }}
syntax is used to use value of template context variables. So use {% template_tag params %}
syntax. Based on your Django version check the related documentation at https://docs.djangoproject.com/en/2.1/howto/custom-template-tags/ (select specific version from very bottom-right).
将 def new_notification(request):
替换为 notifications.py 中的 def new_notification():
,因为您没有向函数传递任何额外参数,同时在模板 base.html
.
中使用模板标签
现在,刷新您的页面,您可以看到结果,就我而言,它正在运行。
我创建了一个自定义的简单标签来计算一个对象并 returns 它。我希望计数显示在导航栏内。因此可以通知用户。
- 我做了一个模板标签并注册了
- 我在 base.html 中加载了标签
- 我在导航栏中使用了标签,因为我希望在那里显示计数。
- 它只过滤字段 "live" 为 false 的对象
- 我在应用程序目录中创建了一个 templatetags 目录。
- 我在 templatetags 里面添加了一个 __ init __.py
notifications.py (templatetags/notifications.py)
from django import template
from home.models import ReportRequests
register = template.Library()
@register.simple_tag
def new_notification(request):
a = ReportRequests.objects.filter(live=False).count()
return a
base.html
{% load notifications %}
<a href="{% url 'home:report_request' %}"><i class="fas fa-inbox"></i><p>Requests</p><span class="badge badge-pill badge-danger">{{ new_notification }}</span></a>
我希望计数会显示在文本旁边,在带有 bootstrap 的徽章内。但是它没有显示任何内容。
您的代码中几乎没有简单的错误。
现在,只需按照以下步骤解决此问题。
在base.html.
中将{{ new_notification }}
替换为{% new_notification %}
Note:
{{ template_context_variable }}
syntax is used to use value of template context variables. So use{% template_tag params %}
syntax. Based on your Django version check the related documentation at https://docs.djangoproject.com/en/2.1/howto/custom-template-tags/ (select specific version from very bottom-right).将
def new_notification(request):
替换为 notifications.py 中的def new_notification():
,因为您没有向函数传递任何额外参数,同时在模板base.html
. 中使用模板标签
现在,刷新您的页面,您可以看到结果,就我而言,它正在运行。