Django custom template function

Template function is used in the template file handler, use the template function is a function template {%}%

1. Create a custom function folder

I want to use a custom template function, then you need to create a folder to hold the files function, but in django name for the custom function folder there is a strict requirement that contain custom template function folder must be called templatetags .

  • First created in the project folder app templates folder
  • Create a template function py file, the file name can be customized, the author here called 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>

Utils% Load%} { , is the introduction of the corresponding template file, compared with the parameter after the function foramtDate

Guess you like

Origin blog.51cto.com/14284354/2412223