基于Pycharm的Python-flask 的学习分享 04

基于Pycharm的Python-flask 的学习分享 04


前言

在 Flask Web 开发中,前端页面的动态渲染与前后端数据交互是核心需求,Jinja2 模板引擎是实现这一需求的关键工具 ------ 它能让 Python 代码与 HTML 高效联动,还通过丰富语法和过滤器灵活处理数据展示逻辑。本文从 Jinja2 页面渲染原理切入,结合实战代码,逐步讲解前后端交互、核心语法(参数传递、条件判断、循环)及过滤器使用,帮助读者快速掌握其在 Flask 项目中的应用,为构建动态 Web 页面奠基。


jinja2的学习分享


一、jinja2页面渲染的基本原理实现与前后端交互

页面动态渲染的基本原理就是运用MVC模式编程在构造的实例化蓝图中把前端html的代码以字符串的形式返回;

代码实现

py 复制代码
main.c:

from flask import Flask
import os

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

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

from controller.index import index
app.register_blueprint(index)

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

===========================================
controller/index:

from flask import Blueprint, render_template

index = Blueprint('index', __name__)

#页面会返回粗体文字
@index.route('/index')
def my_index():
    return "<strong>我是首页</strong>"

#把前端代码当成一个字符串返回出来,就可以把页面渲染起来了
@index.route('/index2')
def my_index2():
    str = """
        <!DOCTYPE html>
        <html>
            <head>
            <meta charset="utf-8"> 
            <title>实现页面跳转</title>
            <style>
            span{
                display: inline-block;
                width: 200px;
                height: 200px;
                line-height: 200px;
                text-align: center;
                background-color: black;
                color: white;
                font-size: 50px;
                }
            </style>
            </head>
            <body>
                <button>点我跳转百度</button>
                <span id="mySpan">5</span>
                <script>

                    var baiduBtn = document.querySelector('button');
                    var mySpan = document.getElementById('mySpan');


                    baiduBtn.addEventListener('click', function(){
                        console.log(location.href);
                        location.href = "https://www.baidu.com";
                    });


                    var timer = 5; 

                    setInterval(function(){
                        if(timer == 0){  
                            location.href = "https://www.baidu.com";
                        }else{
                            mySpan.innerHTML = timer;  
                            timer--; 
                       }
                    }, 1000);
                </script>
        </body>
    </html>
        """
    return str

#最基础的python代码和前端代码联动,实现按钮跳转和5s自动跳转
@index.route('/index3')
def my_index3():
    username = "gao"
    s = "<strong>{}</strong>".format(username)
    return s

#替换字符串中常量,实现按钮跳转并且10s后自动跳转
@index.route('/index4')
def my_index4():
    str = """
        <!DOCTYPE html>
        <html>
            <head>
            <meta charset="utf-8"> 
            <title>实现页面跳转</title>
            <style>
            span{
                display: inline-block;
                width: 200px;
                height: 200px;
                line-height: 200px;
                text-align: center;
                background-color: black;
                color: white;
                font-size: 50px;
                }
            </style>
            </head>
            <body>
                <button>点我跳转百度</button>
                <span id="mySpan">5</span>
                <script>
                    
                    var baiduBtn = document.querySelector('button');
                    var mySpan = document.getElementById('mySpan');

                    
                    baiduBtn.addEventListener('click', function(){
                        console.log(location.href);
                        location.href = "https://www.baidu.com";
                    });

            
                    var timer = {{timer}}; 
                   
                    setInterval(function(){
                        if(timer == 0){  
                            location.href = "https://www.baidu.com";
                        }else{
                            mySpan.innerHTML = timer;  
                            timer--; 
                       }
                    }, 1000);
                </script>
        </body>
    </html>
        """
    str = str.replace("{{timer}}","10")

    return str

#打开同级文件夹中的html文件,并且替换变量
@index.route('/index5')
def my_index5():
    with open("template/index.html",encoding="utf-8") as file:
        html = file.read()
    html = html.replace("{{timer}}", "10")
    return html

#直接打开写好的html模板,并且实现变量赋值,实现前后端联动
@index.route('/index6')
def my_index6():
    t = 7
    return render_template("index.html",timer=t)

=====================================================
template/index.html:
<!DOCTYPE html>
<html>
            <head>
            <meta charset="utf-8"> 
            <title>实现页面跳转</title>
            <style>
            span{
                display: inline-block;
                width: 200px;
                height: 200px;
                line-height: 200px;
                text-align: center;
                background-color: black;
                color: white;
                font-size: 50px;
                }
            </style>
            </head>
            <body>
                <button>点我跳转百度</button>
                <span id="mySpan">5</span>
                <script>

                    var baiduBtn = document.querySelector('button');
                    var mySpan = document.getElementById('mySpan');


                    baiduBtn.addEventListener('click', function(){
                        console.log(location.href);
                        location.href = "https://www.baidu.com";
                    });


                    var timer = {{timer}};

                    setInterval(function(){
                        if(timer == 0){  
                            location.href = "https://www.baidu.com";
                        }else{
                            mySpan.innerHTML = timer;  
                            timer--; 
                       }
                    }, 1000);
                </script>
        </body>
    </html>

二、jinja2三个重点基本语法和过滤器

jinja2中三个重点的基本语法就是参数的传递、if判断、for循环;

更多jinja2过滤器:点击前往查看更多jinja2过滤器

代码实现

py 复制代码
main.c:
from flask import Flask
import os

#指定文件夹
app = Flask(__name__,template_folder='template')

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

from controller.index import index
app.register_blueprint(index)

if __name__ == '__main__':
    app.run()
===========================================
controller/index:
from itertools import count

from flask import Blueprint, render_template,session


index = Blueprint('index', __name__)

@index.route('/index')
def my_index():
    #1.session参数的传递
    session['username'] = "高先生"
    #2.对象传递
    article = {
        "title" : "论python语言的学习难度",
        "count" : 2000,
        "content" : "我是文章<strong>内容</strong>"
    }
    return render_template("index.html",article=article)
    
=====================================================
template/index.html:
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>jinja2中的参数传递、for循环、if判断</title>
</head>
<body>
{#第一步交给jinja2模板引擎,第二步才是HTML,所以注释不能用<!-- --> #}
{#注释的正确写法#}
{#jinja2中参数的传递#}
    <div>{{session.get('username')}},欢迎您登录</div>
    <div>文章的标题是:{{article.title}}</div>
    <div>文章的阅读量是:{{article.count}}</div>
{#jinja2中if、else判断#}
    {% if article.count % 2 == 0 %}
    <div>您的阅读量可以被2整除,是一个偶数</div>
    {% else %}
    <div>您的阅读量可以被2整除,是一个奇数</div>
    {% endif %}
{#jinja2中for循环#}
    {% for i in range(10) %}
    <div>当前循环的次数是{{i+1}}</div>
    {% endfor %}

{#最常用的过滤器#}
    {#实现加粗等#}
    <div>{{article.content | safe}}</div>
    {#实现开头字母大写#}
    <div>{{"hello world" | title}}</div>
    {#实现所有字母大/小写#}
    <div>{{"hello world" | upper}}</div>
    <div>{{"hello world" | lower}}</div>
    {#实现所有字母先大后小写#}
    <div>{{"hello world" | upper | lower}}</div>

{#自定义过滤器,add的实现在主程序里#}
    <div>{{ 1 | add}}</div>
</body>
</html>

总结

本文深入解析了 Flask 中 Jinja2 模板引擎的使用:从页面渲染原理出发,通过 "字符串返回前端代码→读取 HTML 文件渲染→render_template联动" 的代码示例,清晰呈现前后端交互过程;重点剖析参数传递、if 条件判断、for 循环三大核心语法,并结合safe(处理富文本)、title(格式化字符串)等过滤器,展现其在数据展示与逻辑控制上的灵活性。掌握 Jinja2 是 Flask 开发中衔接前后端的关键,能高效实现动态页面渲染,为复杂 Web 功能开发提供有力支撑。

相关推荐
ValhallaCoder8 小时前
hot100-二叉树I
数据结构·python·算法·二叉树
猫头虎9 小时前
如何排查并解决项目启动时报错Error encountered while processing: java.io.IOException: closed 的问题
java·开发语言·jvm·spring boot·python·开源·maven
八零后琐话10 小时前
干货:程序员必备性能分析工具——Arthas火焰图
开发语言·python
青春不朽51211 小时前
Scrapy框架入门指南
python·scrapy
MZ_ZXD00111 小时前
springboot旅游信息管理系统-计算机毕业设计源码21675
java·c++·vue.js·spring boot·python·django·php
全栈老石12 小时前
Python 异步生存手册:给被 JS async/await 宠坏的全栈工程师
后端·python
梨落秋霜12 小时前
Python入门篇【模块/包】
python
阔皮大师13 小时前
INote轻量文本编辑器
java·javascript·python·c#
小法师爱分享13 小时前
StickyNotes,简单便签超实用
java·python