[Answered ]-Django custom filter look up template variable

2👍

The solution is to change your tag into a template tag instead of a filter – filters are supposed to be atomic and independent of context. Something like this should work:

# takes_context allows you access to the outer template context
@register.simple_tag(takes_context=True) 
def my_tag(context, obj, val):
    lookup_dict = context['lookup_obj']
    # Do something with lookup_dict, obj, and val
    # Return something that will be rendered in the template
    return ...

Then in your template:

{% for a in my_list %}
    {% my_tag a 1 %}
{% endfor %}

Note that this is now a tag ({%) instead of a variable ({{).

Leave a comment