JWL
JWL

Reputation: 14211

Django Templates: How best can the output of executing python code in a Django template be suppressed?

Someone has probably encountered this before, and perhaps even the docs provide a solution already, but I couldn't find it yet. My situation is this:

Just to illustrate the REAL PROBLEM: Assuming I have a list that I pass to the template, and which list I iterate over, with a {% for... in one instance, and in the other, I only need to display its first 5 elements only (based on some condition for example, and not just the first 5 elements of the list). Both loops are being used to output a table dynamically. Now, it's the second instance that's tricky... I adopted the solution here, which utilizes a special Counter Class, passed to the template context, and on which one must invoke the Counter.increment method, to be able to increment the counter - which I then use in my conditional statement, to halt execution of the loop.

The challenge:

I currently have code like this:

<script>{{ Counter.reset }}</script>
<table>
...
{% for l in list %}
{%if Counter.counter <= 5 %}
<tr><td>{{ l.some_field }} <span style="display:none">{{ Counter.increment }}</span></td></tr>
{% endif %}
{% endfor %}
</table>

So, how can I just call the Counter.increment method, without needing the <span> inside which I encapsulate it (so the output from that code isn't sent to the browser)? Is it okay to just do:

<tr><td>{{ l.some_field }}{{ Counter.increment }}</td></tr>

The above would work, if Counter.increment doesn't return anything, but what if it does?!

How best can the output of executing python code in a Django template be suppressed then?

Upvotes: 1

Views: 69

Answers (3)

frist
frist

Reputation: 1958

Also you can use with tag and ignore variable:

{% with ignorevar=Counter.increment %}{% endwith %}

Upvotes: 1

R&#233;gis B.
R&#233;gis B.

Reputation: 10618

This is a bit of a hack, but it would solve your problem:

{{ Counter.increment|yesno:"," }}

(See the documentation on the yesno filter)

Upvotes: 1

Ankush Raghuvanshi
Ankush Raghuvanshi

Reputation: 1442

If you only need the top five elements, then I think the right way is to send a list of only top 5 elements from your views to your your html templates in the very first place.

Also, if for some reason, you are not able to do that, then you should there is a thing in Django known as Template Tags where you do all your calculations.

See this -> https://docs.djangoproject.com/en/1.9/howto/custom-template-tags/

And finally if you still want to use Counter.increment, then simply put it inside a div say "count-flag" and using your javascript, hide that div forever on page load:

$(document).on('ready', function(){
    $("#count-flag").hide();
}

So it will not be displayed on your html, but technically this is not the way to do it.

Upvotes: 0

Related Questions