展开
拓展 关闭
订阅号推广码
GitHub
视频
公告栏 关闭

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!!!")
  • 访问
posted @   DogLeftover  阅读(10)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?
历史上的今天:
2022-03-19 mqtt入门(四):客户端sdk
2022-03-19 mqtt入门(三):emqx认证
2022-03-19 mqtt入门(二):emqx安装
2022-03-19 mqtt入门(一):简介
2022-03-19 mybatis puls学习笔记(二)
2022-03-19 mybatis puls学习笔记(一)
点击右上角即可分享
微信分享提示

目录导航