模板变量
项目名/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>
模板过滤器