Django DTL模板使用

模板变量

项目名/booktest/models.py

from django.db import models

# Create your models here.
class BookInfo(models.Model):
    '''图书模型类'''
    btitle = models.CharField(max_length=20,db_column='title')
    bpub_date = models.DateTimeField()
    bread = models.IntegerField(default=0)
    bcomment = models.IntegerField(default=0)
    isDelete = models.BooleanField(default=False)

    # 重新指定数据表的名字
    class Meta:
        db_table='booktest_bookinfo'

项目名/booktest/urls.py

from django.urls import re_path
from .views import *


urlpatterns = [
    re_path('^index$', index),
    re_path('^temp_var$', temp_var),

]

项目名/booktest/views.py

from django.shortcuts import render
from .models import BookInfo


def temp_var(request):
    '''模型变量'''
    my_dict = {'title':'字典键值'}
    my_list = [1,2,3]
    book = BookInfo.objects.get(id=1)
    # 定义模板上下文
    context = {'my_dict':my_dict,'my_list':my_list,'book':book}
    return render(request,'booktest/temp_var.html',context)

templates/booktest/temp_var.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>模板变量</title>
</head>
<body>
 使用字典属性:{{ my_dict.title }}<br/>
 使用列表元素:{{ my_list.1 }}<br/>
 使用对象属性:{{ book.btitle }}<br/>

</body>
</html>

 


 

模板标签

项目名/booktest/models.py

def temp_tags(request):
    '''模板标签'''
    # 1.查找所有图书信息
    books = BookInfo.objects.all()
    return render(request,'booktest/temp_tags.html',{'books':books})

项目名/booktest/urls.py

from django.urls import re_path
from .views import *

urlpatterns = [
    re_path('^temp_tags$', temp_tags),
]

templates/booktest/temp_tags.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>模板标签</title>
    <style>
        .red{background-color: red;}
        .green{background-color: green;}
        .yellow{background-color: yellow;}
    </style>
</head>
<body>
<ul>
    {% for i in books %}
{#        比较符号两边必须要有空格#}
        {% if i.id <= 2 %}
            <li class="red">{{ forloop.counter }}--{{ i.btitle }}</li>
        {% elif i.id < 5 %}
            <li class="green">{{ forloop.counter }}--{{ i.btitle }}</li>
        {% else %}
            <li class="yellow">{{ forloop.counter }}--{{ i.btitle }}</li>
        {% endif %}
{#        // 打印出序列号#}

    {% endfor %}
</ul>

</body>
</html>


 

模板过滤器

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值