在APPchart
中新建一个文件夹,和两个文件,结构如下:
templatetags/
__init__.py
mytags.py
mytags.py
文件中自定义函数
from django import template
register = template.Library()
@register.filter
def startswith(value, start):
"""
实现python中的 startswith py2中多一个unicode
"""
if isinstance(value, (str, unicode)):
return value.startswith(start)
else:
return False
settings.py
中添加注册
'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': {
"mytags": "chart.templatetags.mytags",
},
},
html文件中使用
{% load mytags %}
{% if field|startswith:"http" %}
<td><a href="{{ field }}">{{ field }}</a></td>
{% else %}
<td>{{ field }}</td>
{% endif %}
说明:
{% if field|startswith:"http" %}
相当于:
startswith(field, "http")
分别是第一个和第二个参数
注意:使用模板语言的时候|
两侧不要有空格!!!
参考