zl程序教程

您现在的位置是:首页 >  后端

当前栏目

Python编程:Django自定义模板标签

Pythondjango模板编程 自定义 标签
2023-09-27 14:24:14 时间

在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/