Issue
I have a Jinja2 template where a variable that resolves as a boolean False is being ignored in an {% if %}
statement.
The relevant chunk of the template looks like
{% if user.can_manage_techniques %}j
{% block submenu_items %}
<li class="pure-menu-item"><a href={{ url_for('new_technique') }} class="pure-menu-link">New Technique</a></li>
{% endblock %}
{% endif %}
The user is set in render template as
return render_template('technique_list.j2',
techniques=Technique.find_all(),
**state())
with the state being a function that returns a dict[string, object].
The user that is passed to it is set in the __init__
of the object as a variable - so:
def __init__(self):
self.can_manage_techniques = False
Even when the can_manage_techniques
is false, the list item still renders. How do I make the {% if %}
realise that it is false and go to the {% endif %}
?
I have also tried == true
and sameas true
Solution
I can't reproduce your problem on local with minimal app below:
from flask import Flask, render_template_string
app = Flask(__name__)
@app.route('/')
def hello():
return render_template_string('''
{{ can }}
{% if can %}
{% block submenu_items %}
<li class="pure-menu-item">New Technique</li>
{% endblock %}
{% endif %}
''', can=False)
IMO, the usage is correct, so you may need to check more related code.
I found why this happened after checking your code on GitHub. This issue caused by the template inheritance behavior: In child template, contents outside the block will be skipped.
Since your template is child template, so you need to put the if statements into the block.
Answered By - Grey Li
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.