Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to concisely represent if/else to specify CSS classes in Django templates

In a Django template, I'd like to add CSS classes to a DIV based on certain "conditions", for example:

<div class="pkg-buildinfo 
            {% if v.release.version == pkg.b.release.version %}active{% else %}inactive{% endif %} 
            {% if v.release.version == project.latest.version %}latest{% else %}notlatest{% endif %}">

(note that v is a loop variable; the whole thing is inside a for loop)

The above adds CSS classes "active" or "inactive" and "latest" or "notlatest" based on two conditions.

This is however hard to read and verbose. I discovered that the with statement does not support assigning the value of expressions/conditions (as opposed to complex variables) which is a pity. Is there a better way to do this?

like image 576
Sridhar Ratnakumar Avatar asked Apr 07 '11 16:04

Sridhar Ratnakumar


People also ask

Can CSS be used in Django?

Aside from the HTML generated by the server, web applications generally need to serve additional files — such as images, JavaScript, or CSS — necessary to render the complete web page. In Django, we refer to these files as “static files”.

What does {% %} mean in Django?

{% %} and {{ }} are part of Django templating language. They are used to pass the variables from views to template. {% %} is basically used when you have an expression and are called tags while {{ }} is used to simply access the variable.

What is a more efficient way to pass variables from template to view in Django?

Under normal usage the standard is to use URL (GET) variables when you are retrieving data from the server and to use Form (POST) variables when you want to manipulate (edit/delete) data on the server.


2 Answers

You could put that logic into your view instead, and create attributes on the object that are "active" or "inactive", etc. Then you only have to access the attributes in the template.

like image 96
Ned Batchelder Avatar answered Oct 31 '22 18:10

Ned Batchelder


A custom filter might be a nice alternative.

@register.filter
def active_class(obj, pkg):
    if obj.release.version == pkg.b.release.version:
         return 'active'
    else:
        return 'inactive'

and use it in your template:

<div class="pkg-buildinfo {{ obj|active_class:pkg }}" 
like image 5
Daniel Roseman Avatar answered Oct 31 '22 18:10

Daniel Roseman