2

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.

2 Answers 2

2

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 }}.

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

Comments

0

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 }}

Comments

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.