脚本之家,脚本语言编程技术及教程分享平台!
分类导航

Python|VBS|Ruby|Lua|perl|VBA|Golang|PowerShell|Erlang|autoit|Dos|bat|

服务器之家 - 脚本之家 - Python - Python Django模板系统详解

Python Django模板系统详解

2022-02-27 14:29久醉绕心弦, Python

这篇文章主要介绍Django模板系统Django模板系统的实现代码,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧

设置模板路径

在django项目下创建templats文件来存放html文件

Python Django模板系统详解

为了减少模板加载调用过程及模板本身的冗余代码,Django 提供了一种使用方便且功能强大的 API ,当使用模板加载API时,需要将模板路径告诉框架,在项目settings.py中设置模板路径,如图:

settings.py中的BASE_DIR为项目路径。

Python Django模板系统详解

在TEMPLATES中的BIRS来设置模板路径

Python Django模板系统详解

templates下编写index.html写入如下代码:

!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>首页</title>
</head>
<body>
 <h1>hello world!</h1>
</body>
</html>

视图文件view.py中编写如下代码,通过render渲染html文件:

from django.shortcuts import render

# 获取对应模板通过render渲染
def index(request):
  return render(request, 'index.html')

结果如下:

Python Django模板系统详解

 

模板变量

Django模板中使用{{ }}来表示变量:

{{ 变量名 }}:变量名由字母数字和下划线组成,其值可以是任何数据类型

举例如下:

当模板引擎遇到变量时,会计算该变量,并将其替换为结果

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>首页</title>
</head>
<body>
  <h3>{{ content }}</h3>
  <h3>{{ info }}</h3>
</body>
</html>

view.py中render渲染时通过context以字典形式传递值:

from django.shortcuts import render

def index(request):
	content = 'hello world'
  info = {'name': 'test', 'age': 18}
  return render(request, 'index.html', context={'content': content, 'info': info})

Python Django模板系统详解

模板中支持以下语法:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>首页</title>
</head>
<body>
  <h3>{{ content }}</h3>
  
  <!-- 获取字典中key的值 -->
  <h3>{{ info.name }}</h3>
  
  <!-- 通过索引获取列表的值 -->
  <h3>{{li.1}}</h3>
  
  <!-- 调用不带参数的方法 -->
  <h3>{{ fun }}</h3>
  
  <!-- 获取对象属性 -->
  <h3>{{ obj.name }}</h3>
</body>
</html>

view.py:

from django.shortcuts import  render

def index(request):
  content = 'hello world'
  info = {'name': 'test', 'age': 18}
  li = [1, 2, 3]

  class Obj:
      def __init__(self, name):
          self.name = name

  M = Obj('对象属性:MING')

  def fun():
      return '方法:fun'

  return render(request, 'index.html', context={'content':content,'info': info,'li': li,'fun': fun,'obj': M})

Python Django模板系统详解

 

引用静态文件

首先在项目根目录下创建存放静态文件的目录,并在settings中设置路径,如下:

Python Django模板系统详解

STATIC_URL = '/static/' 

为静态文件引用前缀,当引用文件时代表的是文件根目录,如下:

static代表的是statics

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>首页</title>
</head>
<body>
  <!-- 图片 -->
  <img src="/static/img/123.jpg" render

def index(request):

  return render(request, 'index.html')

Python Django模板系统详解

 

总结

本篇文章就到这里了,希望能够给你带来帮助,也希望您能够多多关注服务器之家的更多内容!

原文链接:https://blog.csdn.net/weixin_42262081/article/details/121129511

延伸 · 阅读

精彩推荐