Python程式設計:Django自定義模板標籤
阿新 • • 發佈:2019-01-03
在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")
分別是第一個和第二個引數
注意:使用模板語言的時候|
兩側不要有空格!!!
參考