3

In a Django model passing a param to a method and using it in the code is easy.

Class Foo(models.Model):
    number = IntegerField()
    ...
    def bar(self, percent):
        return self.number * percent

f = Foo(number=250)
f.bar(10)

The question is how can this be done in the template layer? Somthing like : {{ foo.bar(10) }}

3 Answers 3

4

The simple answer is that you can't do this, which is by design; Django templates are designed to be keep you from writing real code in them. Instead, you'd have to write a custom filter, e.g.

@register.filter
def bar(foo, percent):
    return foo.bar( float(percent) )

This would let you make a call like {{ foo|bar:"250" }} which would be functionally identical to your (non-working example) of {{ foo.bar(250) }}.

Sign up to request clarification or add additional context in comments.

1 Comment

A filter looks like a good idea. I was under the impression that behind the scenes, Django templates somehow convert these params to filters but seems it has to be done manualy which is still cool.
1

By design, Django templates don't allow you to invoke methods directly so you'd have to create a custom template tag to do what you want.

Jinja2 templates do allow you to invoke methods, so you could look into integrating Jinja2 with Django as another option.

Comments

0

Just do this calculation in the view, and not the template.

This is often the solution to many "template language can't do X" problems.

view

foo = Foo(number=250)
foo.bar = foo.bar(10) 
return direct_to_template(request, "foo.html", {'foo': foo})

template

{{ foo.bar }}

1 Comment

I usualy keep my questions very generic.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.