模板基本语法
-
{{ ... }} 用来显示变量
-
{% ... %} 用来控制语句,比如 if 语句,for 语句
-
{# ... #} 用来添加注释
app.py的渲染模版
from flask import Flask, render_template
app = Flask(__name__)
@app.route('/')
def index():
name = 'Foo'
softwares = [
{'title': 'Linux', 'year': '1991'},
{'title': 'Python', 'year': '1992'},
{'title': 'Git', 'year': '2005'},
{'title': 'Flask', 'year': '2010'},
]
return render_template('index.html', name=name, softwares=softwares)
templates/index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Foo</title>
</head>
<body>
<h2>{{ name }}'s list</h2>
<p>{{ softwares|length }} Titles</p> {# 使用 length 过滤器获取 softwares 变量的长度 #}
<ul>
{% for software in softwares %} {# 迭代 softwares 变量 #}
<li>{{ software.title }} - {{ software.year }}</li> {# 等同于 softwares['title'] #}
{% endfor %} {# 使用 endfor 标签结束 for 语句 #}
</ul>
{% if bio %}
{# 这里的缩进只是为了可读性,不是必须的 #}
<footer>
<small>© 2018 <a href="https://github.com/">HelloFlask</a></small>
</footer>
{% else %}
<footer>
<small>© 未知 </small>
</footer>
{% endif %} {# 大部分 Jinja 语句都需要声明关闭 #}
</body>
</html>
最后编辑于 :
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。