136.flask内置jinja2模版使用

文章目录

基本使用

入口

python 复制代码
 # conding:utf-8
import os
from flask import Flask

app = Flask(__name__,template_folder='template')

app.config['SECRET_KEY'] = os.urandom(20)

from controlle.index02 import index02
app.register_blueprint(index02)

# 过滤器
@app.template_filter('add')
def add(input):
    return input+1

# 全局函数
def myadd(a, b):
    return a + b
app.jinja_env.globals.update(myadd=myadd)

if __name__ == '__main__':
    app.run()

controlle.index02

python 复制代码
from flask import  Blueprint, render_template, session

index02 = Blueprint("index02", __name__)

@index02.route("/index02")
def index2_info():
    session["username"] = "大周老师"
    article = {
        "title": "论Python语言的学习难度",
        "count": 2001,
        "content": "<strong>你好</strong>"
    }
    return render_template('index02.html', article=article)

渲染模版

python 复制代码
<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title></title>
	</head>
	<body>
		<button>你好这里是我的第二个模块</button>
		<h1>基本使用</h1>
		<div>标题:{{article.title}}</div>
		<div>阅读次数:{{article.count}}</div>

		{% if article.count % 2 == 0 %}
		<div>这是个偶数</div>
		{% else %}
		<div>这是个基数</div>
		{% endif %}

	    {% set result1 = article.count / 100 %}
	    {% set result2 = result1 | int %}
		<div>当前除以100的结果是: {{result2}}</div>

		{% for i in range(result2) %}
		<div>循环的每一项事: {{i+1}}</div>
		{% endfor %}

		<!--基本过滤器-->
		<div>{{ article.content | safe }}</div>
	    <div>{{ 'hello word' | upper }}</div>
	    <div>{{ 'hello word' | title }}</div>
	    <div>{{ 'hello word' | lower }}</div>

		<!-- 自定义过滤器 -->
		 <div>自定义过滤器{{ 1 | add }}</div>
		 <!-- 全局函数 -->
		 <div>全局函数{{ myadd(1,2) }}</div>
	</body>
</html>
相关推荐
橙露9 分钟前
Python 对接 API:自动化拉取、清洗、入库一站式教程
开发语言·python·自动化
Omigeq15 分钟前
1.4 - 曲线生成轨迹优化算法(以BSpline和ReedsShepp为例) - Python运动规划库教程(Python Motion Planning)
开发语言·人工智能·python·算法·机器人
2301_8084143816 分钟前
自动化测试的实施
开发语言·python
无限码力20 分钟前
华为OD技术面真题 - Python开发 - 4
python·华为od·华为od技术面真题·华为od面试八股文·华为od面试真题·华为odpython开发真题·华为od技术面题目
程序员小崔日记27 分钟前
技术之外,皆是人间
后端·ruoyi·计算机温情
不懂的浪漫1 小时前
# mqtt-plus 架构解析(八):Spring Boot 自动装配,这些零件是怎么被粘合起来的
spring boot·后端·物联网·mqtt·架构
l1t1 小时前
用wsl自带的python 3.10下载适用于3.12的pandas版本结合uv安装python 3.12模拟离线安装场景
python·pandas·uv
开心就好20251 小时前
Flutter iOS应用混淆与安全配置详细文档指南
后端·ios
掘金者阿豪1 小时前
记一次NFS下的权限踩坑:从“Operation not permitted”到安装成功的折腾实录
后端
飞Link1 小时前
【AI大模型实战】万字长文肝透大语言模型(LLM):从底层原理解析到企业级Python项目落地
开发语言·人工智能·python·语言模型·自然语言处理