Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Custom django tag returning a list?

Tags:

python

django

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 ?

like image 392
Torimus Avatar asked Jul 24 '13 14:07

Torimus


1 Answers

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 %}
like image 182
karthikr Avatar answered Sep 29 '22 13:09

karthikr