在Web开发中,直接将HTML代码写在Python文件中会导致诸多问题:
Flask内置了Jinja2模板引擎,完美解决了这些问题。
首先创建项目结构:
myapp/
├── app.py
└── templates/
└── index.htmlapp.py内容:
from flask import Flask, render_template
app = Flask(__name__)
@app.route('/')
def index():
user = {'username': '张三', 'age': 25}
posts = [
{'title': '第一篇', 'content': '内容1'},
{'title': '第二篇', 'content': '内容2'}
]
return render_template('index.html', user=user, posts=posts)
if __name__ == '__main__':
app.run(debug=True)templates/index.html内容:
<!DOCTYPE html>
<html>
<head>
<title>{{ user.username }}的主页</title>
</head>
<body>
<h1>欢迎, {{ user.username }}!</h1>
<p>年龄: {{ user.age }}</p>
<h2>文章列表</h2>
<ul>
{% for post in posts %}
<li>{{ post.title }} - {{ post.content }}</li>
{% endfor %}
</ul>
</body>
</html>render_template()函数的工作流程:
<p>用户名: {{ user['username'] }}</p>
<p>年龄: {{ user.get('age', 18) }}</p> <!-- 带默认值 -->假设我们有一个User类:
class User:
def __init__(self, username, email):
self.username = username
self.email = email模板中可以这样访问:
<p>用户名: {{ user.username }}</p>
<p>邮箱: {{ user.email }}</p><p>第一篇文章: {{ posts[0].title }}</p>
<p>最后一篇文章: {{ posts[-1].title }}</p><p>当前时间: {{ config.DEBUG }}</p> <!-- 访问Flask配置 -->
<p>请求方法: {{ request.method }}</p> <!-- 访问请求对象 -->
<p>会话信息: {{ session.get('user_id') }}</p>
<p>闪现消息: {{ get_flashed_messages() }}</p>Jinja2提供了丰富的内置过滤器:
<!-- 字符串处理 -->
<p>{{ "hello"|capitalize }}</p> <!-- Hello -->
<p>{{ "HELLO"|lower }}</p> <!-- hello -->
<p>{{ "hello world"|title }}</p> <!-- Hello World -->
<p>{{ "hello"|replace("e", "a") }}</p> <!-- hallo -->
<!-- 列表处理 -->
<p>{{ [1,2,3]|length }}</p> <!-- 3 -->
<p>{{ [1,2,3]|first }}</p> <!-- 1 -->
<p>{{ [1,2,3]|last }}</p> <!-- 3 -->
<p>{{ [1,2,3]|join("|") }}</p> <!-- 1|2|3 -->
<!-- 数值处理 -->
<p>{{ 3.1415926|round(2) }}</p> <!-- 3.14 -->
<p>{{ 1000|filesizeformat }}</p> <!-- 1000 Bytes -->
<p>{{ 0.85|float }}</p> <!-- 0.85 -->
<!-- 日期处理 -->
<p>{{ user.create_time|datetimeformat }}</p>
<p>{{ user.create_time|datetimeformat('%Y-%m-%d') }}</p>
<!-- HTML处理 -->
<p>{{ "<script>alert(1)</script>"|escape }}</p>
<p>{{ "Markdown text"|markdown }}</p>
<p>{{ "https://example.com"|urlencode }}</p>在app.py中注册自定义过滤器:
@app.template_filter('reverse')
def reverse_filter(s):
return s[::-1]
@app.template_filter('format_phone')
def format_phone(phone):
return f"{phone[:3]}-{phone[3:7]}-{phone[7:]}"模板中使用:
<p>{{ "hello"|reverse }}</p> <!-- olleh -->
<p>{{ "13812345678"|format_phone }}</p> <!-- 138-1234-5678 -->