Django模板
一、模板基本概念
templates文件夹下面的文件都叫模板文件。只不过有的包含模板语法(在这种情况下,在把html页面发送给客户端之前,会先有一个解析模板语法的过程),有的不包含。

二、使用模板
1.模板引擎配置
settings.py
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'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',
],
},
},
]
2.模板路由配置
urls.py
from django.urls import path
from . import views
app_name = 'blog'
urlpatterns = [
path('home', views.home, name='home'),
]
views.py
from django.shortcuts import render
def home(request):
return render(request, 'home.html')
三、模板语法
1.{% %}
用于渲染标签
(1){% extends '模板名' %}
继承其他模板。
(2){% block 块名 %}
{% block 块名 %}
渲染内容
{% endblock %}
(3){% for 变量 in 可迭代对象 %}
{% for 变量 in 可迭代对象 %}
迭代渲染内容
{% endfor %}
(4){% if 表达式 %}
{% if 表达式 %}
......
{% elif 表达式 %}
......
{% else %}
......
{% endif %}
(5){% load static %}
引入配置的static路径。
{% load static %}
<link rel="stylesheet" type="text/css" href="{% static 'css/style.css' %}">
(6){% url '应用名:模板名' %}
模板之间的跳转链接。
<a href="{% url '应用名:模板名' %}"></a>
2.{{ }}
用于渲染变量
网友评论