Reputation: 39
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
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:
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
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