Python程序教程

您现在的位置是:首页 >  Django

当前栏目

Django模板

Django,模板
2025-04-11 08:58:06 时间

一、模板概述与配置

1、概述

  • 说明 模板是HTML页面,可以根据传递的数据进行填充
  • 组成
    • HTML代码
    • 逻辑控制代码 变量 标签 过滤器
  • 作用 很便利的生成HTML界面
  • 优点 模板的设计实现了业务逻辑与显示内容的分离
  • 处理过程
    • 加载:根据给定的标识找到模板,然后预处理,通常会将它编译好放到内存中
    • 渲染:使用context数据对模板进行插值并返回新生成的字符串

2、创建目录与配置

  • 创建模板存储目录
  • 在应用目录下创建名为templates目录来存放模板
  • 在工程目录下创建名为templates目录来存放模板
  • 将templates标记为模板文件夹 将templates标记为模板文件夹
  • 代码配置 project/settings.py文件 代码58行

添加如下代码

<span class="hljs-string">'DIRS'</span>: [os.path.join(BASE_DIR, <span class="hljs-string">'templates'</span>)],

二、模板定义与变量

1、渲染模板方法

get_template()

render()

导入

from django.template import loader, render

使用loader模块的get_template方法进行渲染

<span class="hljs-keyword">from</span> django.template <span class="hljs-keyword">import</span> loader

template = loader.get_template(<span class="hljs-string">'main/index.html'</span>) <span class="hljs-comment">#返回模板对象</span>
result = template.render({<span class="hljs-string">'data'</span>:<span class="hljs-string">''</span>}) <span class="hljs-comment">#模板对象进行渲染 返回渲染后的模板代码</span>

使用render方法进行渲染

原型:render(request, templateName[, context])

作用: 结合数据和模板,返回完整的HTML页面

参数

  • request 请求体对象
  • templateName 模板路径
  • context 传递给需要渲染在模板上的数据

使用

<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">index</span><span class="hljs-params">(request)</span>:</span>
    <span class="hljs-keyword">return</span> render(request,<span class="hljs-string">'myApp/index.html'</span>,{<span class="hljs-string">'传递给模板的键名'</span>:<span class="hljs-string">"传递过去的数据"</span>})

2、变量

说明

  • 视图传递给模板的数据
  • 要遵守标识符规则
  • 语法 {{ var }}
  • 在模板中使用语法
    • 字典查询
    • 属性或者方法
    • 数字索引
  • 在模板中调用对象的方法
  • 注意
    • 不能传递参数
    • 如果使用的变量不存在,则插入的是空字符串

示例

视图函数

<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">index</span><span class="hljs-params">(request)</span>:</span>
    data = {
        <span class="hljs-comment"># 字典的键到模板中作为变量名使用,该变量的值为当前字典键值对的值</span>
        <span class="hljs-string">"name"</span>: lucky,
        <span class="hljs-string">"age"</span>: <span class="hljs-number">18</span>
    }
    <span class="hljs-keyword">return</span> render(request, <span class="hljs-string">"index.html"</span>, data)

模板

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>template1</title>
</head>
<body>
  <h2>我是非常帅气的 {{ name }} 老师 今年才{{ age }} 岁 </h2>
</body>
</html>