1. 程式人生 > >Python程式設計:Django自定義模板標籤

Python程式設計:Django自定義模板標籤

在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")
分別是第一個和第二個引數

注意:使用模板語言的時候|兩側不要有空格!!!

參考

  1. Django之模板語言
  2. Django: is not a registered tag library.
  3. https://stackoverflow.com/questions/40686201/django-1-10-1-my-templatetag-is-not-a-registered-tag-library-must-be-one-of/42881074
  4. https://docs.djangoproject.com/en/1.10/howto/custom-template-tags/