大家好我是正在学习Django的小白bllli。做项目的时候我发现Django模板不能带参数调用函数
{% for member in group.members.all %}
{% if not group.already_invite(member) %}
可以邀请...
{% else %}
已经邀请了...
{% endif %}
{% endif %}
第二句试图在调用group对象的already_invite方法,来确认这个group是否已经邀请了某个member
然而不行,会报错
查到了这个django模版中带参数调用任意函数的方法 - 为程序员服务。用自定义filter来调用函数,可惜这篇文章说得不够详细
研究了一下,跑起来了
自定义filter
在app目录下创建templatetags包,在包里新建fun_filter.py
templatetags/
├── fun_filter.py
├── __init__.py
fun_filter.py
from django import template
register = template.Library()
@register.filter(name='add_arg')
def template_args(instance, arg):
"""stores the arguments in a separate instance attribute"""
if not hasattr(instance, "_TemplateArgs"):
setattr(instance, "_TemplateArgs", [])
instance._TemplateArgs.append(arg)
return instance
@register.filter(name='call')
def template_method(instance, method):
"""retrieves the arguments if any and calls the method"""
method = getattr(instance, method)
if hasattr(instance, "_TemplateArgs"):
to_return = method(*instance._TemplateArgs)
delattr(instance, '_TemplateArgs')
return to_return
return method()
添加设置
然后在setting的INSTALLED__APP里添加
'backend.templatetags',
(backend是我项目中app的名字)
在模板里加入
{% load fun_filter %}
这是templatetags包中filter文件的名字 (fun_filter.py)
愉快调用
{% if not group|add_arg:member|call:"already_invite" %}
调用group对象的“already_invite”方法,参数为member对象。注意方法名为字符串
完整的
{% for member in users %}
{% if not group|add_arg:member|call:"already_invite" %}{# 未被邀请 #}
邀请
{% else %}
已邀请
{% endif %}
{% endfor %}
Thanks
django模版中带参数调用任意函数的方法 - 为程序员服务
Custom template tags and filters
P.S. 代码实例在这里 https://github.com/bllli/ReverseCourse。