Torimus Torimus - 4 months ago 6
Python Question

Custom django tag returning a list?

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 cann'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 ? Cann't be used directly with some other tag helper ?

Answer

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 %}
Comments