S_Devol
S_Devol

Reputation: 31

How to call a Django function from template and save return in a variable

Context:

I have a piece of HTML that I want to dispaly in the template just in case a function return "true".

Details:

My function

def show_avg_kpi():
    return config.avg_times_visible
register.filter('show_avg_kpi', show_avg_kpi)

Template ( is the piece of code to display or not):

{% if show_avg_kpi %}
  <HTML CODE>
{% endif %}

I want something like this, but I don't know how to save the result of the show_avg_kpi function in a variable to use it with the {% if %} tags

Thank you in advance.

Upvotes: 2

Views: 1721

Answers (2)

Augusto
Augusto

Reputation: 91

I think you could use {% with %} tags. i.e:

{% with my_var=show_avg_kpi %} 
    {% if my_var=condition %}
        HTML CODE
    {% endif %}
{% endwith %}

But you can only use my_var inside the with statement.

Another approach is to send the variable from the view.

Upvotes: 1

Ignacio Villela
Ignacio Villela

Reputation: 150

You can use register.simple_tag like this

@register.simple_tag
def show_avg_kpi():
    return config.avg_times_visible

and in your template like this

{% show_avg_kpi as your_var %}
{% if your_var %}
    your code
{% endif %}

Now show_avg_kpi will be called only once

Upvotes: 1

Related Questions