Jinja2基本使用
控制语句
- templates目录下新建control.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
{% if age>18 %}
<div>您已经满18岁,可以进入网吧!</div>
{% elif age==18 %}
<div>您刚满18岁,需要父母陪同才能进入!</div>
{% else %}
<div>您未满18岁,不能进入网吧!</div>
{% endif %}
{% for book in books %}
<div>图书名称:{{ book.name }},图书作者:{{ book.author }}</div>
{% endfor %}
</body>
</html>
- app.py
@app.route("/control")
def control_statement():
age = 18
books = [{
"name":"三因演义",
"author":"罗贯中"
},{
"name":"水浒传",
"author":"施耐庵"
},]
return render_template("control.html",age=age,books=books)
- 访问
模板继承
- templates目录下新建base.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>{% block title %}{% endblock %}</title>
</head>
<body>
<ul>
<li><a href="#">首页</a></li>
<li><a href="#">新闻</a></li>
</ul>
{% block body %}
{% endblock %}
<footer>这是底部的标签</footer>
</body>
</html>
- child1.html
{% extends "base.html" %}
{% block title %}
我是子模板的标题
{% endblock %}
{% block body %}
我是子模板的body
{% endblock %}
- child2.html
{% extends "base.html" %}
{% block title %}
我是child2
{% endblock %}
{% block body %}
我是child2
{% endblock %}
- app.py
@app.route("/child1")
def child1():
return render_template("child1.html")
@app.route("/child2")
def child2():
return render_template("child2.html")
- 访问
加载静态文件
- app.py
@app.route('/static')
def static_demo():
return render_template("static.html")
- templates/static.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<link rel="stylesheet" href="{{ url_for('static', filename='css/my.css') }}">
<script src="{{ url_for('static',filename='js/my.js')}}"></script>
</head>
<body>
<img src="{{ url_for('static',filename='images/01.jpeg') }}" alt="">
</body>
</html>
- my.css
body{
background-color: pink;
}
- my.js
alert("awsl!!!")
- 访问