Jinja2如果忽略布尔值 [英] Jinja2 If ignores boolean value
问题描述
我有一个Jinja2模板,其中解析为布尔假的变量在 {%if%}
语句中被忽略.
I have a Jinja2 template where a variable that resolves as a boolean False is being ignored in an {% if %}
statement.
模板的相关块看起来像
{% 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())
状态是返回dict [string,object]的函数.
with the state being a function that returns a dict[string, object].
传递给它的用户在对象的 __ init __
中设置为变量-因此:
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
即使 can_manage_techniques
为false,列表项仍会呈现.如何使 {%if%}
意识到它是错误的,然后转到 {%endif%}
?
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 %}
?
我也尝试过 == true
和 sameas true
推荐答案
我无法使用以下最少的应用程序在本地重现您的问题:
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,用法是正确的,因此您可能需要检查更多相关代码.
IMO, the usage is correct, so you may need to check more related code.
在GitHub上检查代码后,我发现了为什么会发生这种情况.此问题是由模板继承行为引起的:在子模板中,块外的内容将被跳过.
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.
由于模板是子模板,因此需要将if语句放入块中.
Since your template is child template, so you need to put the if statements into the block.
这篇关于Jinja2如果忽略布尔值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!