1.新建manage.py文件
from flask import Flask, render_template, render_template_string, g
from flask_script import Manager
app = Flask(__name__)
# 配置自动加载模板文件,调试模式下会自动开启
app.config['TEMPLATES_AUTO_RELOAD'] = True
manager = Manager(app)
@app.route('/')
def index():
# return '模板引擎'
# 渲染模板文件
return render_template('index.html')
# 渲染模板字符串
# return render_template_string('<h1>渲染模板字符串</h1>')
# 使用变量
@app.route('/var/')
def var():
# g是一个全局的对象,该变量不要分配就可以在模板中使用
# 在一次请求上下文中保持不变
g.name = 'xxx'
# return render_template('var.html', name='goudan')
return render_template_string('<h1>Hello {{g.name}}</h1>')
# 使用过滤器
@app.route('/filter/')
def filter():
return render_template('filter.html', name='xiaoming', user='<b>user</b>')
# 流程控制
@app.route('/ctrl/')
def ctrl():
return render_template('ctrl.html', name='lucy')
# 文件包含
@app.route('/include/')
def include():
return render_template('include1.html')
# 宏的使用
@app.route('/macro/')
def macro():
# return render_template('macro.html', name='dahua')
return render_template('macro1.html', name='dahua')
# 模板继承
@app.route('/extends/')
def extends():
return render_template('children.html')
if __name__ == '__main__':
manager.run()
2.各个模板文件
index.html
<h1>模板文件渲染</h1>
var.html
{# 注释:变量应该放在两个大括号中 #}
<h1>hello {{ name }}</h1>
<h1>hello {{ g.name }}</h1>
ctrl.html
{% if name %}
<h1>Hello {{ name }}!</h1>
{% else %}
<h1>Hello World!</h1>
{% endif %}
<ol>
{% for i in range(5) %}
<li>{{ i }}</li>
{% endfor %}
</ol>
fliter.html
<h1>Hello {{ name | upper }}</h1>
{# 过滤HTML标签 #}
<div>{{ user | striptags }}</div>
{# 渲染时不转义 #}
<div>{{ user | safe }}</div>
{# 动态开启关闭转义 #}
{% autoescape False %}
<div>{{ user }}</div>
{% endautoescape %}
include.html
<h1>这是include1.html中的内容</h1>
{% include 'include2.html' %}
include2.html
<div>这是include2.html中的内容</div>
macro.html
{# 定义宏 #}
{% macro show_name(name) %}
<h1>Hello {{ name }}!</h1>
{% endmacro %}
{# 调用宏 #}
{{ show_name(name) }}
macro1.html
{# 导入宏 #}
{% from 'macro.html' import show_name %}
<h1>这是原有的内容</h1>
{# 调用宏 #}
{{ show_name(name) }}
parents.html
<html>
<head>
<meta charset="UTF-8">
<title>{% block title %}基础模板标题{% endblock %}</title>
</head>
<body>
{% block body %}<div>默认内容</div>{% endblock %}
</body>
</html>
children.html
{# 继承自另一个模板 #}
{% extends 'parents.html' %}
{# 根据block可以修改原有的block内容 #}
{% block title %}子模板标题{% endblock %}
{% block body %}
{# 保留基础模板中的内容 #}
{{ super() }}
<div>新加的内容</div>
{% endblock %}