模板任务就是输出数据,输出方式:直接输出,过滤输出,判断输出,循环输出
在Django框架中如何使用模板
1. 在项目的setting.py配置文件中配置模板目录
'DIRS':[os.path.join(BASE_DIR, 'templates')],
2.在应用的视图文件加载模板,并放置要输出的数据
return render(request, "目录/模板文件.html",{放置字典数据})
3.在模板文件中使用变量、标签和过滤器等输出信息
{{变量}} {%标签%} {{变量|过滤器}}
4. views.py
from django.shortcuts import render
from django.http import HttpResponse, JsonResponse
from datetime import datetime
def index(request):
return render(request, "myapp/index.html")
def demo1(request):
context = {}
context['name'] = "Zhangsan"
context['a'] = [10,20,30]
context['stu'] = {"name":"lisi", "age":20}
data = [
{"name":"张翠山", "sex":1, "age":40, 'state':0},
{"name":"殷素素", "sex":0, "age":38, 'state':2},
{"name":"张无忌", "sex":1, "age":20, 'state':1},
{"name":"赵敏", "sex":0, "age":10, 'state':2},
]
context['dlist'] = data
context['time'] = datetime.now
context['m1'] = 100
context['m2'] = 20
return render(request, "myapp/demo1.html", context)
# Create your views here.
def demo2(request):
return render(request, "myapp/demo2.html")
5. myapp/urls.py
from django.contrib import admin
from django.urls import path
from . import views
urlpatterns = [
# path('admin/', admin.site.urls),
path('', views.index, name = 'index'),
path('demo1', views.demo1, name = 'demo1'),
path('demo2', views.demo2, name = 'demo2')
]
6. index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Django框架的Template模板层</title>
</head>
<body>
<h2>Django框架的Template模板层</h2>
<ul>
<li><a href="{% url 'demo1' %}">1.模板的语法</a></li>
<li><a href="{% url 'demo2' %}">2.模板的继承</a></li>
<li><a href="">3.Ajax实战--城市信息级联操作</a></li>
</ul>
</body>
</html>
7. demo1.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<h1>Djanggo的模板语法实例</h1>
<a href="{% url 'index' %}">返回首页</a>
<h3>1. 模板中的变量输出</h3>
<ul>
<li>{{ name }} {{age}}</li>
<li>{{ stu.name}} {{ stu.age }}</li>
<li>{{ a.0 }} {{ a.1 }}</li>
<h3>2. 模板中的标签使用</h3>
<table width="500" border = "1">
<tr>
<th>姓名</th>
<th>性别</th>
<th>年龄</th>
<th>状态</th>
</tr>
{% for vo in dlist %}
<tr>
<th>{{ vo.name }}</th>
<th>{% if vo.sex == 1 %}男{% else %}女{% endif %}</th>
<th>{{ vo.age }}</th>
<th>
{% if vo.state == 0 %}
管理员
{% elif vo.state == 1 %}
VIP账户
{% else %}
<span style = " color:red">禁用账户
</span>
{% endif %}
</th>
</tr>
{% endfor %}
{% csrf_token %}
</table>
<h3>3. 模板中的过滤器使用</h3>
<ul>
<li>原值: {{ name }}</li>
<li>大写: {{ name|upper }}</li>
<li>小写: {{ name|lower }}</li>
<li>{{ time }}</li>
<li>{{ time|date:'Y-m-d' }}</li>
<li>{{ a|join:":" }}</li>
</ul>
</ul>
{# 注释 #}
{% comment %}
多行注释
{% endcomment %}
<h3>4. 模板中的运算</h3>
<ul>
<li>求和:{{ m1|add:m2 }}</li>
<li>求差:{{ m1|add:-20 }}</li>
<li>相乘:{% widthratio m1 1 m2 %}</li>
<li>相除:{% widthratio m1 m2 1 %}</li>
</ul>
</body>
</html>
8. demo2.html
{% extends "myapp/base.html" %}
{% block title2 %}Django的模板继承实例{% endblock %}
9. base.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>{% block title1 %}父模板标题{% endblock %}</title>
</head>
<body>
<h2>{% block title2 %}父模板标题{% endblock %}</h2>
<p>
{% block mycotent %}
此处预留内容区域
{% endblock %}
</p>
</body>
</html>
10. setting
"""
Django settings for tpdemo project.
Generated by 'django-admin startproject' using Django 3.0.
For more information on this file, see
https://docs.djangoproject.com/en/3.0/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/3.0/ref/settings/
"""
import os
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/3.0/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '-%xbk)!4!r&g=n7e1$#hr_$d++3jm@+iv7)po-yxqs2_b%rye4'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = ['*']
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'myapp'
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'tpdemo.urls'
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',
],
},
},
]
WSGI_APPLICATION = 'tpdemo.wsgi.application'
# Database
# https://docs.djangoproject.com/en/3.0/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME':'mytest',
'USER':'root',
'PASSWORD':'hang123',
'HOST':'localhost',
'POST':'3306'
}
}
# Password validation
# https://docs.djangoproject.com/en/3.0/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
# Internationalization
# https://docs.djangoproject.com/en/3.0/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/3.0/howto/static-files/
STATIC_URL = '/static/'