Django学习笔记003——模板渲染

django提供了一个简便的方式,可以直接将模板渲染成字符串和包装成HttpResponse 对象一步到位完成。

示例如下:

from django.shortcuts import render
def book_detail(request):
    return render(request,"detail.html")

在Templates文件下新建模板detail.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>图书详情</title>
</head>
<body>
    <div style="font-size: 50px">您获取的图书详情是XXXX</div>
</body>
</html>

运行项目:

模板查找路径配置如下:

查找顺序:先会在DIRS这个列表中依次查找路径下有没有这个模板,如果有,就返回。如果DIRS列表中所有的路径没有找到,那么先检查当前这个视图所处的app是否已经安装,如果已经安装了,那么就先在当前这个app下的templates文件夹中查找模板,如果没有找到,那么会在其他已经安装了的app中查找,如果所有路径下都没有找到,抛出TemplateDoesNotExist的异常

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',
            ],
        },
    },
]

猜你喜欢

转载自blog.csdn.net/yaoliuwei1426/article/details/82051797
今日推荐