1.创建环境
workon python37_django2 django-admin startproject template cd template python manage.py startapp app
2.模板的基本设置
项目下创建 templates 存放html模板的文件夹
创建模板文件
templates/index.html
{% load static %} <html> </html> <h1> hello {{ name }}</h1> <ul> {% for item in array %} <li>{{ item }} -- {{ forloop.counter0 }} -- {{ forloop.counter }} -- {{ forloop.revcounter }} -- {{ forloop.revcounter0 }} {% if forloop.first %} is first {% elif forloop.last %} is last {% endif %} </li> {% empty %} <li>is empty</li> {% endfor %} </ul> <p> <a href="{% url 'index' 'conan' %}">return</a> </p> {% static 'index.css' %}
templates/base.html
<!DOCTYPE html> <html lang="en"> <head> {% block head %} <meta charset="UTF-8"> <title>{% block title %}{% endblock %}</title> {% block css_style %} {% endblock %} {% endblock %} </head> <body> {% block content %} {% endblock %} {% block js_script %} {% endblock %} </body> </html>
django的settings.py 配置修改
TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', # 添加路径 'DIRS': [os.path.join(BASE_DIR, 'templates')], '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', ], }, }, ]
引入 static/index.css
settings.py配置
STATICFILES_DIRS = (os.path.join(BASE_DIR, 'static'),)
视图的创建
app/views.py
# encoding:utf-8 import datetime from django.shortcuts import render from django.views.generic import View class Index(View): TEMPLATE = 'index.html' def get(self, request, name): data = {} data['name'] = name data['array'] = range(10) return render(request, self.TEMPLATE, data)
创建路由
app/urls.py
# _*_ coding:utf-8 _*_ from django.urls import path from .views import Index urlpatterns = [ path('<str:name>',Index.as_view(), name = 'index') ]
总路由中引入
template/urls.py
from django.contrib import admin from django.urls import path, include from app import urls as app_urls urlpatterns = [ path('admin/', admin.site.urls), path('', include(app_urls)) ]
测试
标签与过滤器的使用
视图中的示例:app/views.py
# encoding:utf-8 import datetime from django.shortcuts import render from django.views.generic import View class Index(View): TEMPLATE = 'index01.html' def get(self, request, name): data = {} data['name'] = name data['array'] = range(10) # data['array'] = [] data['count'] = 20 data['time'] = datetime.datetime.now() data['cut_str'] = "hello-boy!" data['first_big'] = "hello django" # data['result'] = False # data['result'] = [] # data['result'] = None data['result'] = False data['dic_list'] = [{'name':'jack', 'age':30},{'name':'xiaoming','age':18}] data['float_num'] = 3.1415926 data['html_str'] = '<div style="background-color:red;50px;height:50px"></div>' data['a_str'] = '请看 www.baidu.com' data['feature'] = data['time'] + datetime.timedelta(days=5) return render(request, self.TEMPLATE, data)
模板示例 templates/index.html
{% extends 'base.html' %} {% load static %} {% load myfilter %} {% block css_style %} <link rel="stylesheet" href="{% static 'index.css' %}" /> {% endblock %} {% block title %} test {% endblock %} {% block content %} <h1>hello {{ name }}</h1> <ul> {% for item in array %} <li>{{ item }}</li> {% endfor %} </ul> <br /> <label>add : </label>{{ count|add:10 }}<br/> <label>date: </label>{{ time|date:"Y-m-d H:i:s" }}<br/> <label>cut : </label>{{ cut_str|cut:"-" }}<br/> <label>capfirst : </label>{{ first_big|capfirst }}<br/> <label>default:</label>{{ default|default:"空列表" }}<br/> <label>default_if_none:</label>{{ result|default_if_none:"none才是空" }}<br/> <lable>dictsort:</lable>{{ dic_list|dictsort:'age' }}<br/> <label>dictsortreversed:</label>{{ dic_list|dictsortreversed:'age' }} <label>first:</label>{{ dic_list|first }}<br/> <lable>last:</lable>{{ dic_list|last }}<br/> <lable>floatformat: </lable>{{ float_num|floatformat:4 }}<br/> <label>join: </label>{{ array|join:"-" }}<br/> <lable>length: </lable>{{ dic_list|length }}<br/> <lable>divisibleby: </lable>{{ count|divisibleby:3 }}<br/> <label>length_is: </label>{{ dic_list|length_is:2 }}<br/> <lable>html_str: </lable>{{ html_str|safe }}<br/> <lable>random: </lable>{{ dic_list|random }}<br/> <label>slice:</label>{{ html_str|slice:":8" }}<br/> <lable>slugify:</lable>{{ html_str|slugify }}<br/> <lable>upper:</lable>{{ html_str|upper }}<br/> <label>urlize : </label>{{ a_str|urlize }}<br/> <label>wordcount: </label>{{ a_str|wordcount }}<br/> <label>timeutils: </label>{{ feature|timeuntil }}<br/> <label>custom: </label>{{ count|test:10 }} {% endblock %}
显示效果
自定义过滤器的使用:
app/templatetags/myfilter.py
# _*_ coding:utf-8 _*_ # __author__ == 'jack' # __date__ == '2020-12-30 9:53 PM' from django import template register = template.Library() @register.filter def test(value, args): return value * args
使用: 将数字乘以 10 返回结果
<label>custom: </label>{{ count|test:10 }}