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…?
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 %}