Python编程:Django自定义模板标签
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")
分别是第一个和第二个参数
注意:使用模板语言的时候|
两侧不要有空格!!!
参考
相关文章
- Python中如何编写接口,以及如何请求外部接口
- python学习第四讲,python基础语法之判断语句,循环语句
- Python 使用Django
- 1. Python_Django项目之大型电商项目介绍
- python-django
- 【Python】django多对多 查询 ,反查等操作
- 【Python】Django 聚合 Count与Sum用法,注意点
- 【Python】Django CSRF问题
- Python pandas.DataFrame.info函数方法的使用
- 25条Python知识点,面试命中高达95%
- PhEmail:基于Python的开源网络钓鱼攻击工具
- Python Web开发框架Django
- Python基础:编码规范(4)
- WINDOWS+NGINX+DJANGO+FLUP+PYTHON起步~
- 三十八、python学习之Django框架(一):入门,介绍,设计模式,环境搭建,项目创建,基本配置,创建视图,静态文件,路由与反解析,App应用配置
- 四十、python学习之Django框架(二):响应,重定向,