Template variables
Introduction of template variables
Template variable usage rules
1.Language: { { Change amount name }}
2. The name consists of letters, numbers and underscores, and cannot have spaces or punctuation marks.
3. You can use dictionaries, models, methods, functions, and lists
4. Do not have the same name as python or django keywords
5. Variables and search
Notice:
1. If data is a dictionary, then accessing data.items will access the value of the key named items in the data dictionary, but will not access the items method of the dictionary.
2. Points have special meaning when rendering templates. The dot in the variable name indicates search.
Examples of template variables
Take views.py under app-book as an example
ls = [1,2,4,5]
dic = {
"a":1,"b":2}
def hello():
return "django"
class Fruits:
def __init__(self,name,color):
self.name = name
self.color = color
def say(self):
return "HAHAHA"
ap = Fruits("apple","red")
def temp_v(request,**kwargs):
return render(request, 'temp_v.html',
context={
'book':"python",
'hello':hello,
'ls':ls,
'dic':dic,
'fruits':ap,
'fruits_say':ap.say
})
temp-v.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>temp_v</title>
</head>
<body>
{
{ book }}<br>
列表{
{ls.1}}<br>#ls.1表示取列表中第一个元素
字典{
{ dic}}<br>
字典中的键{dic.b}<br>
类{
{ fruits }}<br>
类方法{
{ fruits_say }}<br>
类方法2{
{ fruits.say}}
</body>
</html>
filter
Function: Filter variables. Before actually rendering, the filter will process the variables according to the function, and then replace the original variables and display the results after getting the results.
语法:{ {fruits|lower}}
Commonly used filters
date and time filter format
The modified time is Shanghai time
In the main project settings.py
LANGUAGE_CODE = 'zh-hans'#中国时区 TIME_ZONE = 'Asia/Shanghai'#上海时区
Filter example
def temp(request,**kwargs):
return render(request, 'temp_v.html',
context={
'name':'阿杰 阿佳',
'age':18,
'none':None,
'li':ls,
'dic':dic,
'now':datetime.datetime.now(),
'str':'i love you',
'html':'<i>this is python<i>',
'zy':'大于:> 小于:<',
'float':127.0193,
})
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>temp_v</title>
</head>
<body>
名字:{
{ name }}
名字切除空格:{
{ name|cut:' ' }}<br>
年龄{
{age}}
年龄+1{
{age|add:1}}<br>
空值:{
{ none}}
空值设置:{
{ none|default:'阿佳'}}<br>
列表第一个值:{
{li|first}}
列表最后一个值:{
{li|last}}<br>
日期时间:{
{ now }}<br>
日期:{
{ now|date }}<br>
时间:{
{ now|time }}<br>
日期时间:{
{ now|date:"日期:Y/m/d 时间:H:i:s"}}<br>
字符串拼接{
{ str|join:'-' }}<br>
字符串大写{
{ str|upper }}<br>
切片{
{ str|slice:'2:4'|upper }}<br>
html{
{ html }}<br>
html{
{ html|safe }}<br>
大小于{
{ zy}}<br>
><{
{
zy|safe }}<br>
浮点数{
{ float }}<br>
保留一位小数{
{ float|floatformat }}<br>
保留两位小数{
{ float|floatformat:'2' }}<br>
</body>
</html>
static files
Table of contents
Create static (including css, js, img, etc.) under the main project
Configuration
Add STATICFILES_DIRS in settings.py file
Set the static file directory path, the same as templates*.