Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

django template conditional html

I'm not sure if the title is technically correct (sorry, I'm new to python+django)

I have a template page that displays whether an application is running or stopped depends on its status. For example:

If app is running I want to display:

<div class="lt">
    <a class="play" title="App running">
        <span class="text_play">Running</span>
    </a>
</div>
<div class="rt">
    <input type="submit" onclick="stop_app()" value="stop" class="stop">
</div>

If the application is not running then show this instead:

<div class="lt">
    <input type="submit" onclick="star_app()" value="start" class="play">
</div>
<div class="rt">
    <a class="stop" title="Application is not running">
        <span class="test_stop">Not Running</span>
    </a>
</div>

This is kind of stripped down simplified html but my point is how can I avoid repeating myself?

The template is passed a dictionary of applications that it iterates over to display all the applications and their status (running/stopped). So currently I'm iterating over the dict twice, one for "stopped" apps and one for the "running" apps.

Hope it's clear

Thanks in advance

EDIT: This is what I have tried so far:

{% if application.service.status|lower == "enabled" %} 
<div>...display running HTML...</div>
{% else %}
<div>...display the non-runing HTML..</div>
{% endif %}

I just want to know if I'm doing the right thing (DRY?)

like image 826
Mardanian Avatar asked Apr 26 '14 18:04

Mardanian


1 Answers

What you proposed is pretty DRY.

{% if application.service.status|lower == "enabled" %} 
<div>...display running HTML...</div>
{% else %}
<div>...display the non-runing HTML..</div>
{% endif %

Keep in mind you'll rely on the return render(request... for determining the html Django needs construct.

Your proposed solution will choose one or the other. I.e. if your non-running HTML needs to switch to running HTML you won't have access to it without another render.

To be more clear and concise, django templates will construct the appropriate HTML leaving out the alternative options or "conditions".

If you learn a bit of jQuery for example you can have elements of the page switch the currently displayed html. Expanding this to ajax will allow you to get status updates from the server and vice versa.

like image 170
visc Avatar answered Sep 21 '22 02:09

visc