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

Question:

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?

Asked By: cleg

||

Answers:

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

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.

Answered By: dolma33

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.

Answered By: Marcin

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 %>
Answered By: sherpya

What you could do is, create the “function” as another template file and then include that file passing the parameters to it.

Inside index.html

<h3> Latest Songs </h3>
{% include "song_player_list.html" with songs=latest_songs %}

Inside song_player_list.html

<ul>
{%  for song in songs %}
<li>
<div id='songtile'>
<a href='/songs/download/{{song.id}}/'><i class='fa fa-cloud-download'></i>&nbsp;Download</a>

</div>
</li>
{% endfor %}
</ul>
Answered By: sidmanu