[Answered ]-Django templatetag return True or False

2đź‘Ť

âś…

Your first approach (action_needed tag returning a boolean + if tag) doesn’t work cause a templatetag cannot be used as “argument” for another one, so your {% if action_needed %} try to resolve a variable named action_needed in the context.

If the test (“some_condition”) depends on some object available in the current context you can use a custom filter applied to this object, ie:

@register.filter
def action_needed(obj):
    return some_test_on(obj)

{% if obj|action_needed %}
   whatever
{% endif %}

Else, well, you either have to write an assignment tag setting the flag in the context then test the flag or, like you finally did, write a tag doing both the test and returning the appropriate html snippet.

Just as a side note – this :

exp = Account.objects.filter(expiration_date__lte = timezone.now())
if len(exp) == 0:
    return False
else:
    return True

is a complicated way to write this:

return len(Account.objects.filter(expiration_date__lte=timezone.now())) > 0

which is an inefficient way to write this:

return Account.objects.filter(expiration_date__lte=timezone.now()).exists()

0đź‘Ť

You could create a custom template tag that checks if the condition is met. If it is true then render the html between the tags.

{% block sidebar %}
<div id="content-related">
{% ifaction %}
    <div class="my-module">
        <h2>Foobar</h2>
        <p>Display this over the sidebar</p>
    </div>
{% endifaction %}
... Sidebarstuff...
{% endblock %}

You can see how it is done by looking at the code for Gargoyle’s
ifswitch tag.

👤user2995894

0đź‘Ť

There are a few approaches you could take here. One idea would be to put the some_condition check as a context processor, so it is automatically included in all templates – although that’s overkill if you only want it in one template.

A better approach would be to use an inclusion tag. That way, the code currently inside the {% if action_needed %} tags would be in a separate template snippet that only gets included if the condition is true. Or, you could use an assignment tag to set a variable in the context, then check it within the if.

(Also, note that your code is extremely inefficient, as it potentially involves getting all future Account objects. You should do if exp.exists() to do a simple existence check instead.)

Leave a comment