When using a simple template tag that returns a dictionary:
@register.simple_tag
def get_types():
return {
"item1": "Foo",
"item2": "Bar",
}
This doesn't print any column:
{% for type in get_types.values %}
<th>{{ type }}</th>
{% endfor %}
While this does:
{% get_types as types %}
{% for type in types.values %}
<th>{{ type }}</th>
{% endfor %}
Is there a way to make it work without having to put the temporary variable {% get_types as types %}
? Most questions I found on StackOverflow or in forums are from 2018 or older. I'm wondering if there is a cleaner way to do this 6 years later as I'm not a fan of temporary variables.
No, what you want isn't really possible. {% tag ... %}
is how a template tag is used. When one writes {% for .... %}
one is using the for
template tag.
In the line {% for type in get_types.values %}
the get_types.values
is evaluated as an expression by Django where it looks into the context to find any variables needed. If this would allow us to also utilize other template tags over there it would be ambiguous as to whether one is referring to a template tag or a variable.
If you really want this an alternative would be to create a replacement for the for
template tag and handle all the parsing and calling of other template tags on your own. Please refer to the documentation on advanced custom template tags if you decide to go that way. In my opinion though this would just increase complexity for very little value. It's simpler to do it the way you are already doing it.