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

yipeiwu_com7年前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编程求质数实例代码

Python编程求质数实例代码

本文研究的主要是Python编程求质数实例,选取了几个数进行了测试,具体如下。 定义:质数又称素数。一个大于1的自然数,除了1和它自身外,不能被其他自然数整除的数叫做质数;否则称为合数。...

Python常用库推荐

IPython + ptpython,完美体验 首先是安装 pip install ipython ptpython 然后使用 ptipython 有什么好处 1. IPython...

python中numpy.zeros(np.zeros)的使用方法

翻译: 用法:zeros(shape, dtype=float, order='C') 返回:返回来一个给定形状和类型的用0填充的数组; 参数:shape:形状 dtype:数据类型,可...

python装饰器decorator介绍

一、装饰器decorator decorator设计模式允许动态地对现有的对象或函数包装以至于修改现有的职责和行为,简单地讲用来动态地扩展现有的功能。其实也就是其他语言中的AOP的概念...

Python 除法小技巧

复制代码 代码如下:from __future__ import division print 7/3 输出结果: 2.3333333333...