The Flask Mega-Tutorial Part II:Templates
Jinja2
利用模板能够很好的将业务逻辑层与表现层分开。通常我们将模板放在templates文件夹下,当然该文件夹会包含在应用里面
将模板转换成一完整的HTML页面这一过程称之为'rendering'
模板例子:
#index.html
<html>
<head>
<title>{{ title }} - Microblog</title>
#{{...}}动态内容
</head>
<body>
<h1>Hello, {{ user.username }}!</h1>
</body>
</html>
#routes.py,模板调用
from flask import render_template
from app import app
@app.route('/')
@app.route('/index')
def index():
user = {'username': 'Miguel'}
return render_template('index.html', title='Home', user=user)#传入的是模板,传出来的还是同一个模板,只不过里面的{{...}}被实值代替了
模板同时也支持条件控制,for循环等{%...%}
#index.html
<html>
<head>
{% if title %}
<title>{{ title }} - Microblog</title>
{% else %}
<title>Welcome to Microblog!</title>
{% endif %}
</head>
<body>
<h1>Hello, {{ user.username }}!</h1>
{% for post in posts %}
<div><p>{{ post.author.username }} says: <b>{{ post.body }}</b></p></div>
{% endfor %}
</body>
</html>
#routes.py,模板调用
from flask import render_template
from app import app
@app.route('/')
@app.route('/index')
def index():
user = {'username': 'Miguel'}
posts = [
{
'author': {'username': 'John'},
'body': 'Beautiful day in Portland!'
},
{
'author': {'username': 'Susan'},
'body': 'The Avengers movie was so cool!'
}
]
return render_template('index.html', title='Home', user=user,posts = posts)
模板继承:
block,子模板可以在父模板的block块里插入内容
#base.html
<html>
<head>
{% if title %}
<title>{{ title }} - Microblog</title>
{% else %}
<title>Welcome to Microblog</title>
{% endif %}
</head>
<body>
<div>Microblog: <a href="/index">Home</a></div>
<hr>
{% block content %}{% endblock %}
</body>
</html>
#index.html
{% extends "base.html" %}
{% block content %}
<h1>Hi, {{ user.username }}!</h1>
{% for post in posts %}
<div><p>{{ post.author.username }} says: <b>{{ post.body }}</b></p></div>
{% endfor %}
{% endblock %}

浙公网安备 33010602011771号