Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

django pass parameter to function in template tag

Is it possible to pass a parameter to a function inside of a django template tag?

Defined class and function:

class Bar():

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

in template:

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

Currently I'm getting a TemplateSyntaxError "Could not parse the remainder"

like image 628
MattoTodd Avatar asked May 04 '11 22:05

MattoTodd


1 Answers

You need to import the template library in your file with template filters:

from django import template

register = template.Library()

Then you need to register you template filter function in that file:

@register.filter(name='foo')

Then create your filter function like this in that file:

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

Then you put the file inside your app in this hierarchy:

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

Then to load your foo_functions file in the template you need to run this:

{% load foo_functions %}

Then you use foo like this:

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

You can read more about this at the Django documentation for creating custom template tags.

like image 118
rzetterberg Avatar answered Nov 12 '22 01:11

rzetterberg