11、模板中的可复用代码块

单文件中的宏

模板文件

<!DOCTYPE html>
<html lang="en">
	<head>
		<meta charset="UTF-8" />
		<title>宏的定义和使用</title>
	</head>
	<body>
    {#宏的定义 #}
	  {% macro input(name, type='text', value= '') %}
      <input type="{{ type }}" name="{{ name }}" value="{{ value }}" />
		{% endmacro %}

    {#宏的使用#}
		<div style="color: #0000ff;">
			<p>用户名 :{{ input('username')}}</p>
			<p>密 码 :{{ input('password',type='password')}}</p>
			<p>登 录 :{{ input('submit',type='submit',value='登录')}}</p>
		</div>
	</body>
</html>

主程序文件

from flask import Flask,render_template
app = Flask(__name__)

@app.route('/')
def hello_world():
    return render_template('index.html')
    
if __name__ == '__main__':
    app.run(debug=True)

多文件中的宏

定义宏文件 form.html

{# 定义宏,并且它包含默认值。还可以被多个文件导入 #}
{% macro input(name, type='text', value= '' ,size='20', placeholder='') %}
    <input type="{{ type }}" name="{{ name }}" value="{{ value }}" size="{{ size }}" placeholder="{{ placeholder }}">
{% endmacro %}

定义模板文件 index.html

<!DOCTYPE html>
<html lang="en">
	<head>
		<meta charset="UTF-8" />
		<title>宏的导入</title>
	</head>
	<body>
    {# 导入宏 #}
		{% from 'form.html' import input %}

    {# 使用宏 #}
		<div style="color: #0000ff">
			<p>用户名 :{{ input('username', placeholder='请输入用户名')}}</p>
			<p>密 码 :{{ input('password',type='password', placeholder='请输入密码')}}</p>
			<p>登 录 :{{ input('submit',type='submit',value='登录')}}</p>
		</div>
	</body>
</html>

定义主程序

from flask import Flask,render_template
app = Flask(__name__)

@app.route('/')
def hello_world():
    return render_template('index.html')
    
if __name__ == '__main__':
    app.run()

include 导入模板

include 可以用来导入模板:

定义待导入的模板 header.html

<!DOCTYPE html>
<html lang="en">
	<head>
		<meta charset="UTF-8" />
		<title>Title</title>
	</head>
	<body>
		<div class="header">这是网页头部</div>
	</body>
</html>

定义待导入的模板 footer.html

<!DOCTYPE html>
<html lang="en">
	<head>
		<meta charset="UTF-8" />
		<title>Title</title>
	</head>
	<body>
		<div class="footer">这是网页尾部</div>
	</body>
</html>

定义主模板

<!DOCTYPE html>
<html lang="en">
	<head>
		<meta charset="UTF-8" />
		<title>Title</title>
		<style type="text/css">
			.header {
				width: 100%;
				height: 40px;
				margin: 20px 20px;
			}
			.footer {
				width: 100%;
				height: 40px;
				margin: 20px 20px;
			}
			.content {
				width: 100%;
				height: 40px;
				margin: 20px 20px;
			}
		</style>
	</head>
	<body>
		{% include "header.html" %}{# 导入模板 #}
		<div class="content">这是网页内容</div>
		{% include "footer.html" %}{# 导入模板 #}
	</body>
</html>

定义主程序

from flask import Flask,render_template
app = Flask(__name__)

@app.route('/')
def hello_world():
    return render_template('index.html')
    
if __name__ == '__main__':
    app.run()

参考资料

https://weread.qq.com/web/reader/0a932660718ac6bc0a9702e

posted @ 2022-05-30 10:57  tiansz  阅读(25)  评论(0编辑  收藏  举报