2

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.

2
  • are you using it everywhere in all templates or just in one template ? Commented Mar 7, 2022 at 13:00
  • Just in a one template Commented Mar 7, 2022 at 13:58

2 Answers 2

1

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

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

Comments

1

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.

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.