模板
3、自定义simple_filter ,simple_tag (模板自定义函数)
a、在app中创建templatetags模块
b、创建任意 .py 文件,如:xx.py
from django import template register = template.Library() #register 一词固定写法 @register.filter def my_upper(value): return value.upper() @register.filter def my_u(value,arg): return value+arg @register.filter def my_bool(value): return False @register.simple_tag def my_lower(value,a1,a2,a3): return value + a1 + a2 + a3
c、在使用自定义simple_tag的html文件中导入之前创建的 xx.py 文件名
{% load xx %} {# 导入此句 #} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <h1>打印字典所有的key</h1> {{ name|my_upper }} {{ name|my_u:‘666‘ }} <h2>filter</h2> {{ name|my_u:"666" }} {% if name|my_bool %} <h3>真</h3> {% else %} <h3>假</h3> {% endif %} <h2>tag</h2> {% my_lower "ALEX" "x" "SB" "V" %} </body> </html>
d、在settings中配置当前app,不然django无法找到自定义的simple_tag
INSTALLED_APPS = ( ‘django.contrib.admin‘, ‘django.contrib.auth‘, ‘django.contrib.contenttypes‘, ‘django.contrib.sessions‘, ‘django.contrib.messages‘, ‘django.contrib.staticfiles‘, ‘app01‘, )
时间: 2024-10-11 20:57:54