Erwin Julian
Erwin Julian

Reputation: 39

How to call a variable function with parameter in django template?

I want to achieve something like this within a Django template.

{{ variable.function(parameter) }}

Where variable is a variable passed through a context to a template, in this case, an instance of a model. I have tried different methods, but no one seems to work.

Upvotes: 2

Views: 584

Answers (2)

Paulo Scardine
Paulo Scardine

Reputation: 77251

This is not possible in Django templates: they are crippled on purpose in order to prevent template designers from shooting themselves in the foot. The reasoning is that the only logic in templates should be presentation logic and all business logic should be kept in the view. Some people thinks it is fair enough and some think it is a bit condescending (those dumb template designers are not smart enough to use functions and methods safely).

I can think of 3 choices:

  1. use jinja2 instead.
  2. write a custom template filter.
  3. keep all the logic in the view where Django designers think you are supposed to keep it.

I will not explain how to use Jinja2 because it is already explained in the docs and because the example in the question works verbatim if you switch to it instead of native Django templates. This simply works in Jinja2:

{{ variable.function(parameter) }}

Now the template filter solution: first you must follow a code layout convention. The filter itself would be something like this:

# at your_tag_library.py
@register.filter(name='call_with')
def apply_callable(callable, arg):
    return callable(arg)

Then in the template you can do:

{% load your_tag_library %}

{{ variable.function|call_with:parameter }}

Of course the last option is the one from Daniel's answer - precompute the value in the view and just display the result in the template:

context['result'] = variable.function(parameter) 

And in your template you just need {{ result }}.

Upvotes: 2

Daniel
Daniel

Reputation: 16

There is no way to do this. You can create another variable and pass it through the context so you could use it. Like:

context['result'] = variable.function(parameter) 

In your view. And in your template: {{ result }}

Upvotes: 0

Related Questions