Django-模板使用

-----模板使用
1、配置
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',
],
},
},
]
 
2、定义模板
<!DOCTYPE html><html lang="en"><head>
<meta charset="UTF-8">
<title>Title</title></head><body>
<h1>{{ city }}</h1></body></html>
 
3、模板渲染
from django.http import HttpResponse
from django.template import loader, RequestContext
 
def index(request):
# 1.获取模板
template=loader.get_template('booktest/index.html')
# 2.定义上下文
context=RequestContext(request,{'city': '北京'})
# 3.渲染模板
return HttpResponse(template.render(context))
 
from django.shortcuts import render
 
def index(request):
context={'city': '北京'}
return render(request,'index.html',context)
 
4、模板语法
4-1、模板变量
def index(request):
context = {
'city': '北京',
'adict': {
'name': '西游记',
'author': '吴承恩'
},
'alist': [1, 2, 3, 4, 5]
}
return render(request, 'index.html', context)
 
<!DOCTYPE html><html lang="en"><head>
<meta charset="UTF-8">
<title>Title</title></head><body>
<h1>{{ city }}</h1>
<h1>{{ adict }}</h1>
<h1>{{ adict.name }}</h1> 注意字典的取值方法
<h1>{{ alist }}</h1>
<h1>{{ alist.0 }}</h1> 注意列表的取值方法
</body></html>
 
4-2、模板语句
4-2-1、for循环
{% for item in 列表 %}
 
循环逻辑
{{forloop.counter}}表示当前是第几次循环,从1开始
{%empty%} 列表为空或不存在时执行此逻辑
 
{% endfor %}
 
4-2-2、if条件
{% if ... %}
逻辑1
{% elif ... %}
逻辑2
{% else %}
逻辑3
{% endif %}
 
4-3、过滤器
* safe,禁用转义,告诉模板这个变量是安全的,可以解释执行
* length,长度,返回字符串包含字符的个数,或列表、元组、字典的元素个数。
* default,默认值,如果变量不存在时则返回默认值。
 
4-4、注释
{#...#}
 
{% comment %}
...
{% endcomment %}
 
4-5、模板继承
{% block 名称 %}
预留区域,可以编写默认内容,也可以没有默认内容
{% endblock 名称 %}
 
{% extends "父模板路径"%}
 
{% block 名称 %}
实际填充内容
{{ block.super }}用于获取父模板中block的内容
{% endblock 名称 %}
 
 
 
 

猜你喜欢

转载自www.cnblogs.com/zsmart/p/10034235.html
今日推荐