Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Running quick if statements in Django template language

Tags:

I'm using this code:

<div class="stream {% if streams.online %}online{% else %}offline{% endif %}"> 

It seems a little redundant. I'd love to run this code

<div class="stream {{ 'online' if stream.online else 'offline' }}"> 

But sadly that doesn't work. Is there a shorter and less messy way of doing what I want?

like image 893
Hubro Avatar asked Aug 10 '11 21:08

Hubro


People also ask

How do you do if statements in Django?

How to use if statement in Django template. In a Django template, you have to close the if template tag. You can write the condition in an if template tag. Inside the block, you can write the statements or the HTML code that you want to render if the condition returns a True value.

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 {{ name }} means in a Django template?

What does {{ name }} this mean in Django Templates? {{ name }} will be the output. It will be displayed as name in HTML. The name will be replaced with values of Python variable.


1 Answers

Can't you use the yesno built-in template filter?

As in,

<div class="stream {{ stream.online|yesno:"online,offline" }}"> 
like image 55
André Caron Avatar answered Oct 22 '22 20:10

André Caron