django的template模板
django的template模板
前言
django支持配置template模板,但是默认是没有这个目录的,需要手动进行配置。template模板可以动态生成html网页,它包括部分html代码和一些特殊的语法
目录
创建目录,存放html文件
创建目录
创建一个模板目录, 比如:templates

放入html文件
放入一个html文件,如:index.html

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>template</title>
</head>
<body>
<h1>hello saiya</h1>
</body>
</html>
配置setting
setting.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',
],
},
},
]
在主路由中添加子路由
主路由中的urls.py
from django.contrib import admin
from django.urls import path,include
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('app.urls')),
]
配置子路由urls
app中的子路由urls.py
from django.urls import path
from .views import Index
urlpatterns = [
path('<str:name>', Index.as_view()),
]
配置视图views
views.py
from django.shortcuts import render
from django.views.generic import View
# Create your views here.
class Index(View):
def get(self, request, name):
return render(request, 'index.html')
启动服务,访问服务,即可看到html已经展示成功了:

static静态文件配置
变量与标签
- 变量用双大括号包裹,例如:{{name}}
- 内置标签用一个大括号,大括号里左右两边各一个%,例如:
内置标签
{% for %} {% endfor %} 遍历输出的内容
{% if %} {% elif %} {% endif %} 对变量进行条件判断
{% url name args %} 引用路由配置名
{% load static %} 加载django的标签库
{% static static_path %} 读取静态资源
{% extends base_template %} 模板继承
{% block data %} {% endblock %} 重写父模板的代码
{% csrf_token %} 跨域密钥,一般在表单(form)中使用
for标签模板
forloop.counter 从1开始计算获取当前索引
forloop.counter0 从0开始计算获取当前索引
forloop.revcounter 索引从最大数递减到1
forloop.revcounter0 索引从最大数递减到0
forloop.first 当前元素是否是第一个
forloop.last 当前元素是否是最后一个
empty 为空的情况
静态文件配置setting.py
# 静态文件
STATICFILES_DIRS = [
os.path.join(BASE_DIR, 'static'),
]
浙公网安备 33010602011771号