1、自定义标签
1、自定义标签
配置:
a.在app中新建文件夹 templatetags,里面新建 xx.py文件(如tags.py)
b.tags.py文件中:
#自定义标签
from django import template
register = template.Library()
@register.simple_tag
def render_app_name(admin_class):
return admin_class.model._meta.verbose_name
c.settings文件中配置:
TEMPLATES = [
{
‘BACKEND‘: ‘django.template.backends.django.DjangoTemplates‘,
‘DIRS‘: [os.path.join(BASE_DIR, ‘templates‘)]
,
‘APP_DIRS‘: True,
‘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‘,
],
# 使用自定义标签是,应该加上这个配置,以便于找到tags的位置
‘libraries‘:{
‘tags‘: ‘king_admin.templatetags.tags‘,
}
},
},
]
d、.html文件中
开头处加载:
{% load tags %}
{#加载自定义标签#}
中间处引入:
<tr>
<td>{% render_app_name admin %}</td>
#函数名称 参数
<td>add</td>
<td>change</td>
</tr>
e、给返回的数据起个别名,用as
<tr>
<td>{% render_app_name admin as obj %}</td>
#函数名称 参数 返回的数据的别名为obj
</tr>