Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Conditional 'with' tag in Django

Tags:

python

django

I'm using Django (and Python) for the first time, and I'm looking for the correct solution to an included template that may or may not have been provided with a value.

For example, this template will always have a 'company' defined, but it might not always have a 'user' defined. If the 'user' is not defined, then one should be defined, like so:

<% with guy=(user if user != None else company.admin_user) %>

But I haven't found a good way to accomplish this. In some cases a user will be defined by the includer of the template, in other cases the template should have to find a 'default' user.

Edit: The solution, as per Ignacio's answer, is this:

<% with guy=user|default:company.admin_user %>
like image 314
Craig Otis Avatar asked Apr 02 '12 02:04

Craig Otis


People also ask

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.

How to use if condition in Django templates?

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 is tag in Django?

Django Code The template tags are a way of telling Django that here comes something else than plain HTML. The template tags allows us to to do some programming on the server before sending HTML to the client. template.html : <ul> {% for x in mymembers %} <li>{{ x. firstname }}</li> {% endfor %} </ul> Run Example »


1 Answers

You want the default filter.

like image 103
Ignacio Vazquez-Abrams Avatar answered Sep 21 '22 05:09

Ignacio Vazquez-Abrams