Python Django框架模板渲染功能示例

yipeiwu_com6年前Python基础

本文实例讲述了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 %}

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

希望本文所述对大家基于Django框架的Python程序设计有所帮助。

相关文章

python通过opencv实现图片裁剪原理解析

python通过opencv实现图片裁剪原理解析

这篇文章主要介绍了python通过opencv实现图片裁剪原理解析,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下 图像裁剪的基本概念...

详解pandas库pd.read_excel操作读取excel文件参数整理与实例

详解pandas库pd.read_excel操作读取excel文件参数整理与实例

除了使用xlrd库或者xlwt库进行对excel表格的操作读与写,而且pandas库同样支持excel的操作;且pandas操作更加简介方便。 首先是pd.read_excel的参数:函...

python+selenium 定位到元素,无法点击的解决方法

报错 selenium.common.exceptions.WebDriverException: Message: Element is not clickable at poin...

django 自定义过滤器的实现

自定义模版过滤器 虽然DTL给我们内置了许多好用的过滤器。但是有些时候还是不能满足我们的需求。因此Django给我们提供了一个接口,可以让我们自定义过滤器,实现自己的需求。 模版过滤...

Series和DataFrame使用简单入门

Series和DataFrame使用简单入门

(1)、导入库 from pandas import Series,DataFrame import pandas import numpy (2)、Series简单创建与使用...