【模板语法初识】

【模板语法初识】

将一个字典传给html页面,让页面操作这个字典

jinjia2模块

【1】模板语法之数据交互

<h1>传过来的字典</h1>
{{user}}
<h1>姓名</h1>
{{user.get('username')}}
<h1>年龄</h1>
{{user.age}}
<h1>自定义hobby</h1>
{{user['hobby']}}
  • urls
# -*-coding: Utf-8 -*-
# @File : urls .py
# author: Chimengmeng
# blog_url : https://www.cnblogs.com/dream-ze/
# Time:2023/7/7
from views import *

urls_list = [
    ("/index", index),
    ("/login", login),
    ("/register", register),
    ("/xxx", xxx),
    ("/get_time", get_time),
    ("/get_dict", get_dict)
]

  • main
# -*-coding: Utf-8 -*-
# @File : 02 基于wsgrief .py
# author: Chimengmeng
# blog_url : https://www.cnblogs.com/dream-ze/
# Time:2023/7/6

from wsgiref.simple_server import make_server
from urls import urls_list
from views import *


def main(env, response):
    '''

    :param env: 请求相关的所有数据
    :param response: 相应相关的所有数据
    :return: 返回给浏览器的数据
    '''

    response('200 OK', [])

    # wsgiref 自动处理传进来的数据,封装成字典,更加方便操作
    # 从env中取到请求地址
    current_path = env.get('PATH_INFO')

    # 定义一个变量存储匹配到的函数名
    func = None
    for url in urls_list:
        if current_path == url[0]:
            func = url[1]

            # 匹配正确后,结束当前循环
            break

    # 判断 func 是否有值
    if func:
        # 匹配成功执行方法
        res = func(env)
    else:
        # 匹配失败返回 失败页面
        res = error(env)

    return [res.encode('utf8')]


if __name__ == '__main__':
    ip = '127.0.0.1'
    port = 8080
    server = make_server(ip, port, main)
    # 实时监听 ip:port 地址,只要有人访问就会触发run函数运行

    server.serve_forever()

  • get_dict
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>

    <!--  本地 链接 引入方法  -->
    <!--  Websource 文件夹 拷贝到当前文件夹下即可使用  -->
    <!--  jQuery 文件  -->
    <script src="Websource\jQuery\node_modules\jquery\dist\jquery.min.js"></script>
    <!--  Bootstrap 的 JS 文件 (动画效果需要jQuery)  -->
    <script src="Websource\Bootstrap\js\bootstrap.min.js"></script>
    <!--  Bootstrap 的 CSS 样式文件  -->
    <link rel="stylesheet" href="Websource\Bootstrap\css\bootstrap.min.css">
    <!-- bootstrap-sweetalert(弹框) 的 CSS 文件   -->
    <link rel="stylesheet" href="Websource\bootstrap-sweetalert\dist\sweetalert.css">
    <!-- bootstrap-sweetalert(弹框) 的 JS 文件 -->
    <script src="Websource\bootstrap-sweetalert\dist\sweetalert.js"></script>


    <!--  CDN 链接 引入方法  -->
    <!--  Bootstrap 的 CSS 样式文件  -->
    <link rel="stylesheet" href="https://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/3.4.1/css/bootstrap.min.css">
    <!--  Bootstrap 的 JS 文件 (动画效果需要jQuery)  -->
    <script src="https://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/3.4.1/js/bootstrap.min.js">// bootstrap </script>
    <!--  jQuery 文件  -->
    <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.4/jquery.min.js"> // jquery</script>

    <!--  以下为 css样式书写区  -->
    <style>


    </style>

</head>
<body>
<h1>传过来的字典</h1>
{{user}}
<h1>姓名</h1>
{{user.get('username')}}
<h1>年龄</h1>
{{user.age}}
<h1>自定义hobby</h1>
{{user['hobby']}}



</body>
</html>
  • views
# -*-coding: Utf-8 -*-
# @File : views .py
# author: Chimengmeng
# blog_url : https://www.cnblogs.com/dream-ze/
# Time:2023/7/7
import datetime
import os, sys
import time

BASE_DIR = os.path.dirname(os.path.abspath(__file__))

templates_path = os.path.join(BASE_DIR, 'templates')


def index(env):
    return 'index'


def login(env):
    return 'login'


def register(env):
    return 'register'


def error(env):
    return '404 error'


def xxx(env):
    file_path = os.path.join(templates_path, 'myxxx.html')
    with open(file_path, 'r', encoding='utf8') as f:
        return f.read()


def get_time(env):
    current_time = datetime.datetime.now().strftime('%Y-%m-%d %X')
    # 如何将后端获取到的数据反馈给html页面
    file_path = os.path.join(templates_path, 'my_time.html')
    with open(file_path, 'r', encoding='utf8') as f:
        data = f.read()

    data = data.replace('time', current_time)
    return data


from jinja2 import Template


def get_dict(env):
    user_dict = {
        'username': 'dream',
        'age': 18,
    }

    file_path = os.path.join(templates_path, 'get_dict.html')
    with open(file_path, 'r', encoding='utf8') as f:
        data = f.read()

    tmp = Template(data)
    res = tmp.render(user=user_dict)

    return res


if __name__ == '__main__':
    file_path = os.path.join(templates_path, 'myxxx.html')
    print(file_path)

【2】模板语法之数据交互循环

后端获取数据库中的数据展示到页面中

  • 语法
{% for user_dict in info_data %}
<tr>
    <td>{{user_dict.id}}</td>
    <td>{{user_dict.username}}</td>
    <td>{{user_dict.password}}</td>
    <td>{{user_dict.hobby}}</td>
</tr>
{% endfor %}
  • urls
# -*-coding: Utf-8 -*-
# @File : urls .py
# author: Chimengmeng
# blog_url : https://www.cnblogs.com/dream-ze/
# Time:2023/7/7
from views import *

urls_list = [
    ("/index", index),
    ("/login", login),
    ("/register", register),
    ("/xxx", xxx),
    ("/get_time", get_time),
    ("/get_dict", get_dict),
    ("/get_user", get_user)
]

  • views
# -*-coding: Utf-8 -*-
# @File : views .py
# author: Chimengmeng
# blog_url : https://www.cnblogs.com/dream-ze/
# Time:2023/7/7
import datetime
import os, sys
import time

BASE_DIR = os.path.dirname(os.path.abspath(__file__))

templates_path = os.path.join(BASE_DIR, 'templates')


def index(env):
    return 'index'


def login(env):
    return 'login'


def register(env):
    return 'register'


def error(env):
    return '404 error'


def xxx(env):
    file_path = os.path.join(templates_path, 'myxxx.html')
    with open(file_path, 'r', encoding='utf8') as f:
        return f.read()


def get_time(env):
    current_time = datetime.datetime.now().strftime('%Y-%m-%d %X')
    # 如何将后端获取到的数据反馈给html页面
    file_path = os.path.join(templates_path, 'my_time.html')
    with open(file_path, 'r', encoding='utf8') as f:
        data = f.read()

    data = data.replace('time', current_time)
    return data


from jinja2 import Template


def get_dict(env):
    user_dict = {
        'username': 'dream',
        'age': 18,
    }

    file_path = os.path.join(templates_path, 'get_dict.html')
    with open(file_path, 'r', encoding='utf8') as f:
        data = f.read()

    tmp = Template(data)
    res = tmp.render(user=user_dict)

    return res


import pymysql


def get_user(env):
    conn = pymysql.connect(
        host='127.0.0.1',
        port=3306,
        user='root',
        password='1314521',
        database='day08',
        charset='utf8',
        autocommit=True,

    )
    cursor = conn.cursor(cursor=pymysql.cursors.DictCursor)

    sql = 'SELECT * FROM userinfo'

    result = cursor.execute(sql)

    data_list = cursor.fetchall()  # [{},{}]

    file_path = os.path.join(templates_path, 'dict_info.html')
    with open(file_path, 'r', encoding='utf8') as f:
        info_data = f.read()
    tep = Template(info_data)

    res = tep.render(info_data=data_list)

    return res


if __name__ == '__main__':
    # file_path = os.path.join(templates_path, 'myxxx.html')
    # print(file_path)
    get_user('1')

  • main
# -*-coding: Utf-8 -*-
# @File : 02 基于wsgrief .py
# author: Chimengmeng
# blog_url : https://www.cnblogs.com/dream-ze/
# Time:2023/7/6

from wsgiref.simple_server import make_server
from urls import urls_list
from views import *


def main(env, response):
    '''

    :param env: 请求相关的所有数据
    :param response: 相应相关的所有数据
    :return: 返回给浏览器的数据
    '''

    response('200 OK', [])

    # wsgiref 自动处理传进来的数据,封装成字典,更加方便操作
    # 从env中取到请求地址
    current_path = env.get('PATH_INFO')

    # 定义一个变量存储匹配到的函数名
    func = None
    for url in urls_list:
        if current_path == url[0]:
            func = url[1]

            # 匹配正确后,结束当前循环
            break

    # 判断 func 是否有值
    if func:
        # 匹配成功执行方法
        res = func(env)
    else:
        # 匹配失败返回 失败页面
        res = error(env)

    return [res.encode('utf8')]


if __name__ == '__main__':
    ip = '127.0.0.1'
    port = 8080
    server = make_server(ip, port, main)
    # 实时监听 ip:port 地址,只要有人访问就会触发run函数运行

    server.serve_forever()

  • divt_info
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>

    <!--  本地 链接 引入方法  -->
    <!--  Websource 文件夹 拷贝到当前文件夹下即可使用  -->
    <!--  jQuery 文件  -->
    <script src="Websource\jQuery\node_modules\jquery\dist\jquery.min.js"></script>
    <!--  Bootstrap 的 JS 文件 (动画效果需要jQuery)  -->
    <script src="Websource\Bootstrap\js\bootstrap.min.js"></script>
    <!--  Bootstrap 的 CSS 样式文件  -->
    <link rel="stylesheet" href="Websource\Bootstrap\css\bootstrap.min.css">
    <!-- bootstrap-sweetalert(弹框) 的 CSS 文件   -->
    <link rel="stylesheet" href="Websource\bootstrap-sweetalert\dist\sweetalert.css">
    <!-- bootstrap-sweetalert(弹框) 的 JS 文件 -->
    <script src="Websource\bootstrap-sweetalert\dist\sweetalert.js"></script>


    <!--  CDN 链接 引入方法  -->
    <!--  Bootstrap 的 CSS 样式文件  -->
    <link rel="stylesheet" href="https://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/3.4.1/css/bootstrap.min.css">
    <!--  Bootstrap 的 JS 文件 (动画效果需要jQuery)  -->
    <script src="https://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/3.4.1/js/bootstrap.min.js">// bootstrap </script>
    <!--  jQuery 文件  -->
    <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.4/jquery.min.js"> // jquery</script>

    <!--  以下为 css样式书写区  -->
    <style>


    </style>

</head>
<body>

<div class="container">
    <div class="row">
        <div class="col-md-8 col-md-offset-2">
            <h1 class="text-center">用户数据</h1>
            <table class="table table-hover table-striped">
                <thead>
                <th>ID</th>
                <th>USERNAME</th>
                <th>PASSWORD</th>
                <th>HOBBY</th>
                </thead>
                <tbody>
                {% for user_dict in info_data %}
                <tr>
                    <td>{{user_dict.id}}</td>
                    <td>{{user_dict.username}}</td>
                    <td>{{user_dict.password}}</td>
                    <td>{{user_dict.hobby}}</td>
                </tr>
                {% endfor %}
                </tbody>

            </table>
        </div>
    </div>
</div>

</body>
</html>
posted @ 2023-07-07 09:49  Chimengmeng  阅读(5)  评论(0编辑  收藏  举报
/* */