我正在尝试使用 Flask 构建一个网站,但遇到了错误jinja2.exceptions.TemplateSyntaxError: Encountered unknown tag 'endfor'. Jinja was looking for the following tags: 'endblock'. The innermost block that needs to be closed is 'block'。当我尝试使用 localhost:5000 登录本地网页时,出现上述错误。
我已通读回溯错误,它似乎发生在我的 index.html 文件的第 21 行。
{% block content %}
<h1>Hi, {{ current_user.username }}!</h1>
{% if form %}
<form action="" method="post">
{{ form.hidden_tag() }}
<p>
{{ form.post.label }}<br>
{{ form.post(cols=32, rows=4) }}<br>
{% for error in form.post.errors %}
<span style="color: red;">[{{ error }}]</span>
{% endfor %}
</p>
<p>{{ form.submit() }}</p>
</form>
{% endif %}
{ % for post in posts %}
{% include '_post.html' %}
{% endfor %}
<p>
{{ post.author.username }} says <b>{{ post.body }}</b>
</p>
{% endblock %}
Run Code Online (Sandbox Code Playgroud)
预期结果是我能够登录本地 Flask 网站并查看网页上其他用户的帖子。
小智 8
你有一个错字,在第二个 for 循环中
{ % for post in posts %}
{% include '_post.html' %}
{% endfor %}
Run Code Online (Sandbox Code Playgroud)
它应该像下面这样:
{% for post in posts %}
{% include '_post.html' %}
{% endfor %}
Run Code Online (Sandbox Code Playgroud)
原因:{由于前面有空格,%Jinja 不会将其识别为 endfor 标签。从而给你错误。