【python】Django自定义模板函数

参考:https://blog.csdn.net/wenyuanhai/article/details/73656761

注意:

1、自定义模板函数的路径必须为APP的templatetags下:app/templatetags/name.py

2、相同路径下需要touch __init__.py

3、项目settings.py中按照以下修改

INSTALLED_APPS = [
    ...,
    'appname.templatetags.filename',
]

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': ['./template'],
        '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',
            ],
        'libraries':{
            'functionname': 'appname.templatetags.filename',
            }
        },
    },
]

4、模板中添加注册的自定义函数

{% extends "base.html" %}
{% load unixtime_format %}
...
<td>{{ time_int | function name }}</td>
...

猜你喜欢

转载自www.cnblogs.com/jiangxu67/p/9356477.html