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实现鸢尾花三种聚类算法(K-means,AGNES,DBScan)

python实现鸢尾花三种聚类算法(K-means,AGNES,DBScan)

一.分散性聚类(kmeans) 算法流程: 1.选择聚类的个数k. 2.任意产生k个聚类,然后确定聚类中心,或者直接生成k个中心。 3.对每个点确定其聚类中心点。 4.再计算其聚类新中心...

mac下如何将python2.7改为python3

mac下如何将python2.7改为python3

1.查看当前电脑python版本 python -V  // 显示2.7.x 2.用brew升级python brew update python  3.如果安装...

Python 中PyQt5 点击主窗口弹出另一个窗口的实现方法

Python 中PyQt5 点击主窗口弹出另一个窗口的实现方法

1.先使用Qt designer设计两个窗口,一个是主窗口,一个是子窗口    ...

python使用xlrd与xlwt对excel的读写和格式设定

前言 python操作excel主要用到xlrd和xlwt这两个库,即xlrd是读excel,xlwt是写excel的库。本文主要介绍了python使用xlrd与xlwt对excel的读...

tensorflow实现加载mnist数据集

tensorflow实现加载mnist数据集

mnist作为最基础的图片数据集,在以后的cnn,rnn任务中都会用到 import numpy as np import tensorflow as tf import matpl...