Python Django,模板,模板渲染

项目名/settings.py(项目配置,配置模板文件的路径):

import os

# 项目目录的绝对路径
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))


TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [os.path.join(BASE_DIR, 'templates')],   # 设置模板文件目录(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',
            ],
        },
    },
]

应用名/views.py(视图,使用模板的详细步骤):

from django.http import HttpResponse
from django.template import loader,RequestContext


# 定义视图函数 (必须传递HttpRequest参数)  (需要在urls.py中配置路由)
def index(request):
    # 1.获取模板
    template = loader.get_template('应用名/index.html')   # 需要在settings.py中配置模板目录
    # 2.定义上下文 (分配的模板变量)
    context = RequestContext(request,{'title':'图书列表','list':range(10)})
    # 3.渲染模板并返回 (生成html内容)
    return HttpResponse(template.render(context))


应用名/views.py(视图,使用模板的简单写法,render):

from django.shortcuts import render  # 导入render

# 视图函数
def index(request):
    context = {'title':'图书列表','list':list(range(1,10))}   # 字典,分配给模板的变量
    return render(request,'应用名/index.html',context)  # render对模板的使用步骤进行了封装。 第三个参数可以省略不写  

templates/应用名/index.html(模板文件,需要手动创建,settings.py中配置模板路径):

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>模板文件</title>
</head>
<body>
<h1>这是一个模板文件</h1>
使用模板变量:<br/>
{{ title }}<br/>
使用列表:<br/>
{{ list }}<br/>
for循环:<br/>
<ul>
    {% for i in list %}
        <li>{{ i }}</li>
    {% endfor %}
</ul>
</body>
</html>

模板变量使用:{{ 模板变量名 }}

模板代码段:{% 代码段 %}

for循环:

    {% for i in list %}

    {% empty %}

        如果遍历的list是空列表,就会显示该内容。

    {% endfor %}

模板文件的加载(查找)顺序:

猜你喜欢

转载自blog.csdn.net/houyanhua1/article/details/84936822