【问题标题】:for-in-if in jinja2 throws exceptionjinja2 中的 for-in-if 抛出异常
【发布时间】:2016-01-06 13:45:30
【问题描述】:

我是 Python 和 Jinja2 的新手。我想在列表的字典中读取一个值。我认为这种操作有答案here。不幸的是,这似乎在 Jinja2 中不起作用。我明白了:

jinja2.exceptions.TemplateSyntaxError:遇到未知标签“项目”。

据我所知,Jinja2 不理解完整的 Python,我认为这是问题的核心。谁能确认一下?

【问题讨论】:

  • 谁能确认一下? 如果你愿意分享引发此错误的代码..

标签: python jinja2


【解决方案1】:

使用 Flask 的示例:

main.py

from flask import Flask, render_template

app = Flask(__name__)

@app.route('/')
def hello_world():
    dicts = [
        { "name": "Tom", "age": 10 },
        { "name": "Mark", "age": 5 },
        { "name": "Pam", "age": 7 },
        { "name": "Dick", "age": 12 }
    ]
    return render_template("test.html", dicts = dicts)

if __name__ == '__main__':
    app.run(debug = True)

在文件夹模板中

test.html

<html>
<head>
<table>
   <tr>
    <th>Name</th>
    <th>Age</th>
   </tr>
{% for dic in dicts %}
    {%if dic['name'] == 'Pam'%}
        <tr><td><b>{{dic['name']}}</b></td><td><b>{{dic['age']}}</b></td></tr>
    {%else%}
        <tr><td>{{dic['name']}}</td><td>{{dic['age']}}</td></tr>
    {%endif%}
{% endfor %}
</table>
</body>
</html>

输出:

【讨论】:

  • 谢谢我把它分解成 for..in 和 if。这行得通!
猜你喜欢
  • 2023-03-27
  • 2013-05-24
  • 2019-08-08
  • 2021-03-01
  • 2013-09-28
  • 2012-01-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多