【问题标题】:django pass parameter to function in template tagdjango 将参数传递给模板标签中的函数
【发布时间】:2011-08-18 22:14:58
【问题描述】:

是否可以将参数传递给 django 模板标签内的函数?

定义的类和函数:

class Bar():

    def foo(self, value):
       # do something here
       return True

在模板中:

{% if my_bar.foo:my_value %}Yes{% endif %}

目前我收到 TemplateSyntaxError "Could not parse the rest"

【问题讨论】:

    标签: django django-templates


    【解决方案1】:

    您需要使用模板过滤器在文件中导入模板库:

    from django import template
    
    register = template.Library()
    

    然后您需要在该文件中注册您的模板过滤功能:

    @register.filter(name='foo')
    

    然后在该文件中创建像这样的过滤器函数:

    @stringfilter
    def foo(value):
        value = #do something with value
        return value #return value
    

    然后你将文件放在你的应用程序中的这个层次结构中:

    app/
        models.py
        templatetags/
            __init__.py
            foo_functions.py
        views.py
    

    然后要在模板中加载你的 foo_functions 文件,你需要运行这个:

    {% load foo_functions %}
    

    然后你像这样使用 foo:

    {% if my_value|foo %}Yes{% endif %}
    

    您可以在Django documentation for creating custom template tags 上阅读更多相关信息。

    【讨论】:

      猜你喜欢
      • 2020-07-06
      • 2021-06-05
      • 2011-04-18
      • 2011-01-08
      • 2017-08-11
      • 2010-12-26
      • 2015-05-16
      • 1970-01-01
      • 2014-07-14
      相关资源
      最近更新 更多