I'd need to create a custom tag returning a list I can then walk through with {% for item in custom_tag_returning_list %}
.
Now I've made a following hack using assign_tag method, but doubt if it's the right way:
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')
In a template I can't use all_products
directly but need to assign to some variable first:
{% all_products as all_products_list %}
{% if all_products_list %}
{% for product in all_products_list %}
...
{% endfor %}
{% endif %}
Is it necessary to do an assignment to a temporary variable ? Can't be used directly with some other tag helper ?
This looks perfectly fine to me.
Alternatively, for some reason if you cannot pass the product_list
through the view's context, you can use an inclusion tag if you feel that is cleaner:
@register.inclusion_tag("tags/products_list.html")
def all_products():
return {'products_list': Product.objects.order_by('name') }
products_list.html
{% for product in products_list %}
.........
{% empty %}
Empty list
{% endfor %}
and in the html file, you would just do
{% all_products %}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With