How to call function that takes an argument in a Django template?

I'm passing to Django's template a function, which returns some records. I want to call this function and iterate over its result.

{% for item in my_func(10) %} 

That doesn't work. I've tried to set the function's return value to a variable and iterate over the variable, but there seems to be no way to set a variable in a Django template.

Is there any normal way to do it?


Solution 1:

You cannot call a function that requires arguments in a template. Write a template tag or filter instead.

Solution 2:

if you have an object you can define it as @property so you can get results without a call, e.g.

class Item:
    @property
    def results(self):
        return something

then in the template:

<% for result in item.results %>
...
<% endfor %>

Solution 3:

I'm passing to Django's template a function, which returns me some records

Why don't you pass to Django template the variable storing function's return value, instead of the function?


I've tried to set fuction's return value to a variable and iterate over variable, but there seems to be no way to set variable in Django template.

You should set variables in Django views instead of templates, and then pass them to the template.

Solution 4:

By design, Django templates cannot call into arbitrary Python code. This is a security and safety feature for environments where designers write templates, and it also prevents business logic migrating into templates.

If you want to do this, you can switch to using Jinja2 templates (http://jinja.pocoo.org/docs/), or any other templating system you like that supports this. No other part of django will be affected by the templates you use, because it is intentionally a one-way process. You could even use many different template systems in the same project if you wanted.