Home > Software design >  django template for loop if nothing found for specific hostname create a blank cell
django template for loop if nothing found for specific hostname create a blank cell

Time:09-02

I am aggregating multiple outputs from models into the same table. So I am looking for a hostname_id, which ties the models together, and then displaying the output. The problem is there may not be data to display which throws off the alignment of the table so I need to create blank cells.

    {% for y in cpuAverageReport %}
        {% if x.id == y.hostName_id %}
            <td>{{ y.average | floatformat:0}}%</td>
            <td>{{ y.maximum | floatformat:0}}%</td>
        {% endif %}
    {% endfor %}

So if, at the end of the loop, the if argument is never matched I want to create two blank cells. I tried using {% with var="something" %} to tag when the if argument is matched but the {% endwith %} tag must be before the endif tag rendering it useless...

CodePudding user response:

I would say figure out if there's matches in the view and then pass it to the template. From what I'm reading the template shouldn't be handling stuff like this and it should be in the view
I looked into template tags, but at the end of the day it's not much different that figuring it out in the view and passing it to the template

Like you I looked into using with and that's a no-go, unfortunately, as you cant change the values of a with :( bummer!

Finally you could do a JavaScript onload: check if table has rows, if not: create one it's iffy style wise, but it would work.

CodePudding user response:

Could you not just add on an {% else %} with the empty cells to the end of the {% if %} statement?

{% for y in cpuAverageReport %}
    {% if x.id == y.hostName_id %}
        <td>{{ y.average | floatformat:0}}%</td>
        <td>{{ y.maximum | floatformat:0}}%</td>
    {% else %}
        <td></td>
        <td></td>
    {% endif %}
{% endfor %}
  • Related