1、Janja2模板中代码的重复使用,有多种方法:
1)宏的引用:
首先在项目的目录下新建templates文件夹,然后在文件夹中新建一个macro.html,内容如下:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
{% macro render_comment(comment) %}
<li>{{ comment }}</li>
{% endmacro %}
</body>
</html>
其次在templates文件夹中新建一个for.html,重复使用宏,内容如下:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>for_test</title>
</head>
<body>
{% import 'macro.html' as macros%}
<ul>
{% for comment in comments %}
{{ macros.render_comment(comment) }}
{% endfor %}
</ul>
</body>
</html>
Python代码如下:
from flask import Flask
from flask import render_template
from flask_script import Manager
app=Flask(__name__)
@app.route('/')
def for_test():
comments=['navy','luo','123','bnm']
return render_template('for.html',comments=comments)
if __name__=='__main__':
app.run()
执行结果如下:
2)重复利用代码片段
在common.html的文件中写上如下内容:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1>我是重复代码段</h1>
</body>
</html>
在index01.html中写上如下内容:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Hello</title>
</head>
<body>
{% include 'common.html'%}
</body>
</html>
代码如下:
from flask import Flask
from flask import render_template
app=Flask(__name__)
@app.route('/')
def common():
return render_template('index01.html')
if __name__ == '__main__':
app.run()
执行结果:
3)继承基类模板
新建一个base.html里面内容如下:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
{% block head %}
<title>
{%block title%}
{% endblock %} -Application
</title>
{% endblock %}
</head>
<body>
{% block body%}
{% endblock %}
</body>
</html>
新建一个index02.html,内容如下:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
{% extends 'base.html'%}
{%block title%}
flask
{%endblock %}
{%block head %}
{{super()}}
{%endblock %}
{%block body%}
hello word
{%endblock %}
</body>
</html>
;Python代码:
from flask import Flask
from flask import render_template
app=Flask(__name__)
@app.route('/')
def common():
return render_template('index02.html')
if __name__ == '__main__':
app.run()
执行结果: