templates

  • Django自带的是DTL(Django Templates language)
    • DTL模版是一种带有特殊语法的HTML文件。
      • 该文件可以被Django编译
      • 可以传递参数进去
      • 实现数据动态化
    • 编译完成后,生成一个普通的HTML文件

渲染模版方式

  1. render_to_string()找到模版,然后将模版编译后渲染成Python的字符串格式。最后再通过HttpResource类包装成一个HttpResponse对象返回 ```python from django.template.loader import render_to_string from django.http import HttpResponse

def return_page(request): html = render_to_string(“page.html”) return HttpResponse(html)

  1. 2. `render()`直接将模板渲染称字符串和包装成`HttpResponse`对象一步到位完成。**推荐该方法**
  2. ```python
  3. from django.shortcuts import render
  4. from django.http import HttpResponse
  5. def return_page(request):
  6. return render(request, "page.html")
  1. render_to_response将被render取代,功能一致

模版查找路径

  • setting.py中查看

    1. # 该配置包含了模板引擎的配置、模板查找路径的配置、模板上下文的配置等。
    2. TEMPLATES = [
    3. {
    4. 'BACKEND': 'django.template.backends.django.DjangoTemplates',
    5. 'DIRS': [os.path.join(BASE_DIR, 'templates')] #自定义templates文件夹的绝对路径
    6. ,
    7. 'APP_DIRS': True, #开启App内查找templates文件夹下的html
    8. 'OPTIONS': {
    9. 'context_processors': [
    10. 'django.template.context_processors.debug',
    11. 'django.template.context_processors.request',
    12. 'django.contrib.auth.context_processors.auth',
    13. 'django.contrib.messages.context_processors.messages',
    14. ],
    15. },
    16. },
    17. ]
  • 模板查找路径

    • DIRS:一个列表,存放所有的模板路径。
    • APP_DIRS :默认为True,为True时,会在INSTALLED_APP已安装的APP下的templates文件夹(注意文件夹名一定是templates)中查找模板
      • 如果为False,就只在DIRS中查找
  • 模板查找顺序
    1. 会先在DIRS这个列表中一次找到路径下有无该模板,如果有,则返回
    2. 如果没有,则检查当前视图函数所处的app是否已经安装,如果已经安装,则就先该app下的templates文件夹中查找模板
    3. 如果没有,则检查其他已经安装的app下的templates文件夹
    4. 如果没有,则抛出TemplateDoesNotExist的异常
    • 优先级DIRS>本app的templates文件夹>其他app的templates文件夹