Torimus Torimus - 1 year ago 75
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()

def all_products():
return Product.objects.all().order_by('name')

In a template I cann't use
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 Source

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:

def all_products():
    return {'products_list': Product.objects.order_by('name') }


{% for product in products_list %} 
{% empty %}
  Empty list
{% endfor %}

and in the html file, you would just do

{% all_products %}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download