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?
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”.
{% %} 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.
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.
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.
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 }}"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With