您当前的位置: 首页 >  彭世瑜 Python

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

彭世瑜 发布时间:2018-12-19 23:13:11 ,浏览量:3

在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" %}
                 
关注
打赏
1688896170
查看更多评论
0.0539s