django模板渲染


前言

前面介绍了django项目创建,今天在项目里面解析模板部分


一、模板作用

模板是一个文本,用于分离文档的表现形式和内容

二、渲染变量到模板

在项目目录下新建一个templates文件夹,作用是存放模板文件
在这里插入图片描述
新建一个index.html文件

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>Content Page</title>
</head>
<body>
    <p>{{hello}}</p>
    {% comment %} <p>{{变量名}}</p> {% endcomment %}
</body>
</html>

修改模板文件的路径,修改project/settings.py,修改 TEMPLATES 中的 DIRS 为 [os.path.join(BASE_DIR, 'templates')]

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        # 'DIRS': [],
        'DIRS': [os.path.join(BASE_DIR, 'templates')],       # 修改位置(这里需要在头部增加一行 import os,不然会报错)
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

在project项目下增加一个contents.py,写入内容

from django.shortcuts import render
 
def content(request):
    # {"HTML变量名" : "views变量名"}
    return render(request, 'index.html', {'hello' : 'Hello World!'})

在urls.py文件中增加信息:
在这里插入图片描述

访问http://127.0.0.1:8000/content
在这里插入图片描述

三、渲染列表/字典到模板

在index.py里面新增方法

def lists(request):
    data = ["第一条数据","第二条数据","第三条数据"]
    my_list = [
        {'1': 'value1', '2': 'value2'},
        {'k3': 'v3', 'ke4': 'val4'},
    ]
    return render(request,"list.html", {"list":data, "my_list":my_list})

在templates新增list.html

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>Content Page</title>
</head>
<body>
    <p>取出整个列表:</p>
    <p>{{ list }}</p>
    <p>取出列表的第一个元素</p>
    <p>{{ list.0 }}</p>

    <p>使用for循环取出list列表的每个元素:</p>
    <ul>
        {% for item in list %}
            <li>值:{{item}}</li>
        {% endfor %}
    </ul>


    <p>使用for循环取出my_list列表中每个字典的键值对:</p>
    <ul>
        {% for dict_item in my_list %}
            <li>
                <ul>
                    {% for key, value in dict_item.items %}
                        <li>{{ key }}: {{ value }}</li>
                    {% endfor %}
                </ul>
            </li>
        {% endfor %}
    </ul>
</body>
</html>

在urls.py引入from .index import listspath('lists', lists),
访问http://127.0.0.1:8000/lists
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值