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 pandas修改列属性的方法详解

使用astype如下: df[[column]] = df[[column]].astype(type) type即int、float等类型。 示例: import panda...

python plotly画柱状图代码实例

python plotly画柱状图代码实例

这篇文章主要介绍了python plotly画柱状图代码实例,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下 代码 import p...

python中ConfigParse模块的用法

本文实例讲述了python中ConfigParse模块的用法,分享给大家供大家参考。具体方法如下: 写配置一般用ConfigParse.RawConfigParse类 读配置用Conf...

python3实现二叉树的遍历与递归算法解析(小结)

python3实现二叉树的遍历与递归算法解析(小结)

1、二叉树的三种遍历方式 二叉树有三种遍历方式:先序遍历,中序遍历,后续遍历 即:先中后指的是访问根节点的顺序 eg:先序 根左右 中序 左根右 后序 左右根 遍历总体思路:将树分成最小...

使用python动态生成波形曲线的实现

使用python动态生成波形曲线的实现

效果是这个样子的: 用到的模块: * matplotlib.pyplot * matplotlib.animation.FuncAnimation * numpy 三个圆的半径分...