Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Templatetag not working in Django 4.2 template IF condition

I have a Django 4.2 project. For an extra Templatetag I created this simple_tag.

@register.simple_tag(takes_context=True)
def user_help(context):
    # True if HELP is ON for user
    u = context['request'].user

    if u.needs_help:
        return True
    else:
        return False

In the HTML template, I try to catch that Tag in an IF statement, to display help to the user, if needed, like this:

<p>{% user_help %}</p>
{% if user_help %}
<h2>Some help text</h2>
{% endif %}

Although the p-statement shows True in the rendered template, the If condition part of the template is not shown…?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

What am I getting wrong here?

>Solution :

Django templates have a distinction between variable names and template tags, so you can not just use a template tag in an if condition. You need to store it in a helper variable:

<p>{% user_help as uh %}{{ uh }}</p>
{% if uh %}
  <h2>Some help text</h2>
{% endif %}

That being said, I don’t really see why you need a template tag for this, this is equivalent to:

<p>{{ user.needs_help }}</p>
{% if user.needs_help %}
  <h2>Some help text</h2>
{% endif %}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading