[Answered ]-Handling a conditional block in a custom Django template tag

1👍

As it turns out, this is indeed possible. There’s a typo in the if_has_permission routine:

nodelist_true = parser.parse(('endif_has_permission'),)

should instead become:

nodelist_true = parser.parse(('endif_has_permission',))

Note that the comma was in the wrong place! The parse function expects a tuple. Fixing this typo prevents things from going awry.

As an aside, I stumbled upon this question today after running into the exact same problem. Imagine my surprise when I found that I was the original asker, nearly five years ago; ha!

1👍

Templatetags are not like blocks – think about them more like as methods. The error you are getting is due to bad syntax then.

To implement something like this just create a filter that will check a condition (exactly like your tag is doing now) and will return True or False then use it like

    {% if request|your_filter_name:"condition" %}
        <p> do_sth </p>
    {% endif %}

by using default django-template if block


Please notice that you cannot use tags in if blocks – that’s why you need to change it to being filter (by adding register.filter instead of register.tag). Nothing will change but syntax:

    request|your_filter:"condition"

instead of

    your_tag request "condition"

Leave a comment