我需要创建一个返回列表的自定义标签,然后我可以使用{% for item in custom_tag_returning_list %}
.
现在我使用以下方法进行了黑客攻击分配标签方法,但怀疑这是否是正确的方法:
from django import template
from product.models import Product
register = template.Library()
@register.assignment_tag
def all_products():
return Product.objects.all().order_by('name')
在我无法使用的模板中all_products
直接但需要先分配给某个变量:
{% all_products as all_products_list %}
{% if all_products_list %}
{% for product in all_products_list %}
...
{% endfor %}
{% endif %}
是否有必要对临时变量进行赋值?不能直接与其他标签助手一起使用吗?
这对我来说看起来非常好。
或者,由于某种原因,如果您无法通过product_list
通过视图的上下文,您可以使用包含标签 https://docs.djangoproject.com/en/dev/howto/custom-template-tags/#inclusion-tags如果你觉得这样更干净:
@register.inclusion_tag("tags/products_list.html")
def all_products():
return {'products_list': Product.objects.order_by('name') }
产品列表.html
{% for product in products_list %}
.........
{% empty %}
Empty list
{% endfor %}
在 html 文件中,你只需这样做
{% all_products %}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)