【jinja2】flask和jinja2配合使用

简介: 【jinja2】flask和jinja2配合使用

jinja2简介

  • 特征
  • 沙箱中执行
  • 强大的 HTML 自动转义系统保护系统免受 XSS
  • 模板继承
  • 及时编译最优的 python 代码
  • 可选提前编译模板的时间
  • 易于调试。异常的行数直接指向模板中的对应行。
  • 可配置的语法
  • Jinja 分隔符

Jinja 在模板字符串中使用各种分隔符。

  • {% %}-陈述
  • {{ }}-要打印到模板输出的表达式
  • {# #}-模板输出中未包含的注释
  • # ##-行语句

模板渲染

  • app.py
1. from flask import Flask,render_template,request
2. app = Flask(__name__)
3. 
4. @app.route('/')
5. def hello_world():
6. return render_template('index.html')
7. 
8. @app.route('/blog/<int:blog_id>')
9. def blog(blog_id):
10.     page = request.args.get('page', default=1, type=int)
11. return render_template('blog.html',id=blog_id,page=page)
12. 
13. if __name__ == '__main__':
14.     app.run()
  • index.html
1. <!DOCTYPE html>
2. <html lang="en">
3. <head>
4. <meta charset="UTF-8">
5. <title>coleak's page</title>
6. </head>
7. <body>
8. <h1>START</h1>
9. <h2>coleak2</h2>
10. <h3>coleak3</h3>
11. <h4>coleak4</h4>
12. <h5>coleak5</h5>
13. <h1>END</h1>
14. </body>
15. </html>
  • blog.html
1. <!DOCTYPE html>
2. <html lang="en">
3. <head>
4. <meta charset="UTF-8">
5. <title>Title</title>
6. </head>
7. <body>
8. <h1>这里是第{{ id }}位博客主的第{{ page }}页博客</h1>
9. </body>
10. </html>
  • 效果测试
1. http://10.133.5.113:8000
2. http://10.133.5.113:8000/blog/3
3. http://10.133.5.113:8000/blog/3?page=6

模板访问变量属性

  • app.py
1. from flask import Flask,render_template,request
2. app = Flask(__name__)
3. 
4. class user:
5. def __init__(self,username,email):
6.         self.username=username
7.         self.email=email
8. 
9. @app.route('/')
10. def hello_world():
11.     User=user('coleak','123@163.com')
12.     person={
13. "username":"coleak",
14. "email":"123@666.com"
15.     }
16. return render_template('index.html',user=User,person=person)
17. 
18. @app.route('/blog/<int:blog_id>')
19. def blog(blog_id):
20.     page = request.args.get('page', default=1, type=int)
21. return render_template('blog.html',id=blog_id,page=page)
22. 
23. if __name__ == '__main__':
24.     app.run()
  • index.html
1. <!DOCTYPE html>
2. <html lang="en">
3. <head>
4. <meta charset="UTF-8">
5. <title>coleak's page</title>
6. </head>
7. <body>
8. <h1>START</h1>
9. <div><h1>welcome {{ user.username }}</h1></div>
10. <div><h1>你的别名是{{ person.username }},邮箱是{{ person["email"] }}</h1></div>
11. <h2>coleak2</h2>
12. <h3>coleak3</h3>
13. <h4>coleak4</h4>
14. <h5>coleak5</h5>
15. <h1>END</h1>
16. </body>
17. </html>
  • 效果测试

内置过滤器的使用

可以将过滤器应用于数据以对其进行修改。 例如,sum 筛选器可以对数据求和,escape 筛选器对它们进行转义,sort 筛选器对它们进行排序。

  • app.py
1. from flask import Flask,render_template,request
2. app = Flask(__name__)
3. 
4. class user:
5. def __init__(self,username,email):
6.         self.username=username
7.         self.email=email
8. 
9. @app.route('/')
10. def hello_world():
11.     User=user('coleak','123@163.com')
12.     person={
13. "username":"coleak",
14. "email":"123@666.com"
15.     }
16. return render_template('index.html',user=User,person=person)
17. 
18. @app.route('/filter')
19. def filter():
20.     User1=user('coleak',-123.456)
21. return render_template("filter.html",user=User1)
22. 
23. if __name__ == '__main__':
24.     app.run()
  • filter.html
1. <!DOCTYPE html>
2. <html lang="en">
3. <head>
4. <meta charset="UTF-8">
5. <title>过滤器</title>
6. </head>
7. <body>
8. <div>{{ user.username }}长度为{{ user.username|length }}</div>
9. <div>{{ user.email }}绝对值为{{ user.email|abs }}</div>
10. </body>
11. </html>
  • 效果测试

自定义过滤器

  • app.py
1. from flask import Flask,render_template,request
2. from datetime import datetime
3. app = Flask(__name__)
4. 
5. def my_filter(value,format="%Y年-%m月-%d日 %H时:%M分"):
6. return value.strftime(format)
7. 
8. class user:
9. def __init__(self,username,email):
10.         self.username=username
11.         self.email=email
12. app.add_template_filter(my_filter,"time_filter")
13. 
14. @app.route('/')
15. def hello_world():
16.     User=user('coleak','123@163.com')
17.     person={
18. "username":"coleak",
19. "email":"123@666.com"
20.     }
21. return render_template('index.html',user=User,person=person)
22. 
23. @app.route('/filter')
24. def filter():
25.     mytime=datetime.now()
26.     User1=user('coleak',-123.456)
27. return render_template("filter.html",user=User1,mytime=mytime)
28. 
29. if __name__ == '__main__':
30.     app.run()
  • filter.html
1. <!DOCTYPE html>
2. <html lang="en">
3. <head>
4. <meta charset="UTF-8">
5. <title>过滤器</title>
6. </head>
7. <body>
8. <div>{{ mytime }}过滤后为{{ mytime|time_filter }}</div>
9. </body>
10. </html>
  • 效果测试

控制语句

  • app.py
1. from flask import Flask,render_template,request
2. from datetime import datetime
3. app = Flask(__name__)
4. 
5. class user:
6. def __init__(self,username,email):
7.         self.username=username
8.         self.email=email
9. 
10. @app.route('/')
11. def hello_world():
12.     User=user('coleak','123@163.com')
13.     person={
14. "username":"coleak",
15. "email":"123@666.com"
16.     }
17. return render_template('index.html',user=User,person=person)
18. 
19. @app.route('/control')
20. def control():
21.     age=request.args.get('age')
22.     age=int (age)
23.     books=[{"name":"boo1",'price':12},{"name":"boo2",'price':18},{"name":"book3",'price':21}]
24. return render_template('control.html',age=age,books=books)
25. 
26. if __name__ == '__main__':
27.     app.run()
  • control.html
1. <!DOCTYPE html>
2. <html lang="en">
3. <head>
4. <meta charset="UTF-8">
5. <title>控制语句</title>
6. </head>
7. <body>
8. <div>
9.     {% if age>18 %}
10. <h2>可以进入网吧</h2>
11.     {% elif age==18 %}
12. <h2>家长陪同下进入网吧</h2>
13.     {% else %}
14. <h2>不可以进入网吧</h2>
15.     {% endif %}
16. </div>
17. <div>
18.     {% for book in books %}
19. <p>名称:{{ book.name }}</p>
20. <p>价格:{{ book.price }}</p>
21.     {% endfor %}
22. </div>
23. </body>
24. </html>
  • 效果测试

模板继承

模板继承是一项强大的功能,可减少代码重复并改善代码组织。 我们定义了一个基本模板,其他模板文件也从中继承。 这些模板文件将覆盖基本模板文件的特定块。

  • app.py
1. from flask import Flask,render_template,request
2. from datetime import datetime
3. app = Flask(__name__)
4. 
5. class user:
6. def __init__(self,username,email):
7.         self.username=username
8.         self.email=email
9. 
10. @app.route('/')
11. def hello_world():
12.     User=user('coleak','123@163.com')
13.     person={
14. "username":"coleak",
15. "email":"123@666.com"
16.     }
17. return render_template('index.html',user=User,person=person)
18. 
19. @app.route('/base')
20. def base():
21. return render_template("base.html")
22. @app.route('/ch1')
23. def ch1():
24. return render_template("ch1.html")
25. @app.route('/ch2')
26. def ch2():
27. return render_template("ch2.html")
28. 
29. 
30. if __name__ == '__main__':
31.     app.run()
  • base.html
1. <!DOCTYPE html>
2. <html lang="en">
3. <head>
4. <meta charset="UTF-8">
5. <title>{% block title %}{% endblock %}</title>
6. </head>
7. <body>
8. {% block body %}
9. {% endblock %}
10. </body>
11. </html>
  • ch1.html
1. {% extends "base.html" %}
2. {% block title %}
3.     ch1的标题
4. {% endblock %}
5. {% block body %}
6. <div>ch1的body</div>
7. {% endblock %}
  • ch1.html
1. {% extends "base.html" %}
2. {% block title %}
3.     ch2的标题
4. {% endblock %}
5. {% block body %}
6. <div>ch2的body</div>
7. {% endblock %}

加载静态文件

  • 结构框架

  • add.py
1. from flask import Flask,render_template,request
2. from datetime import datetime
3. app = Flask(__name__)
4. 
5. class user:
6. def __init__(self,username,email):
7.         self.username=username
8.         self.email=email
9. 
10. @app.route('/')
11. def hello_world():
12.     User=user('coleak','123@163.com')
13.     person={
14. "username":"coleak",
15. "email":"123@666.com"
16.     }
17. return render_template('index.html',user=User,person=person)
18. 
19. @app.route('/static')
20. def static_use():
21. return render_template("static.html")
22. 
23. if __name__ == '__main__':
24.     app.run()
  • static.html
1. <!DOCTYPE html>
2. <html lang="en">
3. <head>
4. <meta charset="UTF-8">
5. <title>static</title>
6. <link rel="stylesheet" href="{{ url_for('static',filename="css/style.css") }}">
7. <script src="{{ url_for('static',filename="js/myjs.js") }}"></script>
8. </head>
9. <body>
10. <img src="{{ url_for('static',filename="images/flask.jpg") }}"></img>
11. </body>
12. </html>
  • myjs.js
alert('coleak');
  • style.css
1. body{
2. background-color: pink;
3. }
  • flask.jpg

  • 效果测试

目录
相关文章
|
4月前
|
API 网络架构 开发者
Flask Web开发基础【路由和Jinja2模板引擎】
# Flask Web开发基础 Flask是轻量级Web框架,专注于核心功能:请求响应、模板渲染和URL路由。本文档介绍了使用Flask的基础知识,包括命令行和Python两种运行模式,以及如何修改入口文件、端口和地址。此外,还讨论了URL路由的概念和其在Flask中的实现,展示了动态路由和多URL绑定的例子。最后,提到了Jinja2模板引擎,解释了其基本语法,并通过电影列表案例展示了如何结合Flask使用模板。
63 1
|
前端开发 JavaScript 数据处理
Flask之jinja2模板(一)
Flask之jinja2模板(一)
|
前端开发 JavaScript Python
Flask之jinja2模板(三)
Flask之jinja2模板(三)
|
索引 Python
Flask之jinja2模板(二)
Flask之jinja2模板(二)
|
Python
Python编程:Flask或者Jinja2时间格式化
Jinja2 模板支持python函数,直接使用事件对象的方法 格式化即可
147 0
|
前端开发 JavaScript Java
Python Flask 编程 | 连载 09 - Jinja2 模板特性
Python Flask 编程 | 连载 09 - Jinja2 模板特性
Python Flask 编程 | 连载 09 - Jinja2 模板特性
Python Flask 编程 | 连载 08 - Jinja2 过滤器
Python Flask 编程 | 连载 08 - Jinja2 过滤器
Python Flask 编程 | 连载 08 - Jinja2 过滤器
|
缓存 前端开发 Python
Python Flask 编程 | 连载 07 - Jinja2 语法
Python Flask 编程 | 连载 07 - Jinja2 语法
Python Flask 编程 | 连载 07 - Jinja2 语法
|
存储 前端开发 Python
Python Flask 编程 | 连载 06 - Jinja2 语法
Python Flask 编程 | 连载 06 - Jinja2 语法
Python Flask 编程 | 连载 06 - Jinja2 语法
|
XML 数据格式 Python
Python Flask 编程 | 连载 05 - Jinja2 模板引擎
Python Flask 编程 | 连载 05 - Jinja2 模板引擎
Python Flask 编程 | 连载 05 - Jinja2 模板引擎