django pass parameter to function in template tag
是否可以将参数传递给Django模板标签内部的函数?
定义的类和功能:
1 2 3 4 5 | class Bar(): def foo(self, value): # do something here return True |
在模板中:
1 | {% if my_bar.foo:my_value %}Yes{% endif %} |
当前我正在收到TemplateSyntaxError "无法解析剩余部分"
您需要使用模板过滤器将模板库导入文件中:
1 2 3 | from django import template register = template.Library() |
然后您需要在该文件中注册模板过滤器功能:
1 | @register.filter(name='foo') |
然后在该文件中创建过滤器函数,如下所示:
1 2 3 4 | @stringfilter def foo(value): value = #do something with value return value #return value |
然后将文件放入此层次结构中的应用程序中:
1 2 3 4 5 6 | app/ models.py templatetags/ __init__.py foo_functions.py views.py |
然后将您的foo_functions文件加载到模板中,您需要运行以下命令:
1 | {% load foo_functions %} |
然后您像这样使用foo:
1 | {% if my_value|foo %}Yes{% endif %} |
您可以在Django文档中了解有关创建自定义模板标签的更多信息。