[英]How to create a custom template tag that passes in a dictionary of more than one object in django
我想創建一個傳入對象字典的模板標簽
模型.py
class Notification(models.Models):
name = models.CharField()
..........
template_tag.py
創建了一個模板標簽來獲取我想要顯示的所有對象
from django import template
register = template.Library()
@register.simple_tag
def notifications():
context = {'notifications':Notification.objects.order_by('-date')[:4]}
return context
后者啟動一個顯示對象的forloop
{% load template_tag %}
{% for obj in notifications %}
<a href="">{{ obj.name }}</a>
{% endfor %}
希望你明白這個想法......
就像在 python 中一樣:
{% for key, value in notifications.items %}
<a href="#">{{key}} - {{value}}</a>
{% endfor %}
就如此容易!
在做了一些研究之后,我發現 django 被稱為“inclusion_tag” https://docs.djangoproject.com/en/3.2/howto/custom-template-tags/#inclusion-tags
創建一個 html 文件並將其命名為“notifications.html”
@register.inclusion_tag('notifications.html')
def notifications(total = 5):
context = {'notifications':Notification.objects.order_by('-date')[:total]}
return context
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.