Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django custom template-tag not rendered in loop

My Custom tag:

# app/templatetags/ctags.py

def getgenre():
    genre = ["Test1", "Test2"]
    return genre

register.simple_tag(getgenre)

My html:

# app/templates/base.html

{% load ctags %}
<!-- {% getgenre %} -->
{% for genre in getgenre %}
    <li>{{genre}}</li>
{% endfor %}

This renders a blank page for me. If I uncomment {% getgenre %}, django renders ["Test1", "Test2"] as expected. I've tried countless variations of setting up my tag (including the non-simple_tag way) to no avail. I am simply unable to iterate over any value returned by one of my custom-tags.

Am I missing something fundamental here?

like image 914
MoorzTech Avatar asked Dec 26 '22 00:12

MoorzTech


1 Answers

You shoud use assignment_tag instead of simple_tag:

@register.assignment_tag
def getgenre():
    genre = ["Test1", "Test2"]
    return genre

And then in the template:

{% load ctags %}
{% getgenre as genre_list %}
{% for genre in genre_list %}
    <li>{{genre}}</li>
{% endfor %}
like image 185
catavaran Avatar answered Jan 06 '23 09:01

catavaran