Django自定义模板函数

模板函数是使用于模板文件的处理函数,模板函数的使用方式是{% 模板函数 %}

1. 创建自定义函数文件夹

想要使用自定义模板函数的话需要先创建用于存放函数的文件夹,而在django中对于自定义函数文件夹的名称有严格的要求,即要求存放自定义模板函数的文件夹必须叫templatetags

  • 首先在项目app文件夹中创建templates文件夹
  • 创建模板函数py文件,文件名可自定义,笔者这里叫utils.py
    templates/utils.py
    
    from django import template
    from django.utils.safestring import mark_safe
    from time import strftime, localtime

register = template.Library()

@register.simple_tag
def foramtDate(timestamp):
'''
格式化时间戳
'''
result = '1997-01-01 0:0:0'
try:
timestamp = float(timestamp)
result = strftime('%Y-%m-%d %H:%M:%S', localtime(timestamp))
except Exception as error:
pass

return result
**上面内容除了def方法体外,其余均为模板函数固定格式**

#### 2. 在模板文件中使用自定义模板函数
在使用自定义模板函数前需要先引进模板函数文件
```html
{% extends 'global.html' %}
{% load utils %}
<!DOCTYPE html>
<html lang="zh">
.....
<body>
...
<label>注册时间:</label>
<div>{% foramtDate request.session.userData.reg_datetime %}</div>
...
</body>
</html>

{% load utils %},则是引进对应的模板文件,函数foramtDate后面跟的则为形参

猜你喜欢

转载自blog.51cto.com/14284354/2412223