Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django {% with %} tags within {% if %} {% else %} tags?

So I want to do something like follows:

{% if age > 18 %}     {% with patient as p %} {% else %}     {% with patient.parent as p %}     ... {% endwith %} {% endif %} 

But Django is telling me that I need another {% endwith %} tag. Is there any way to rearrange the withs to make this work, or is the syntactic analyzer purposefully carefree in regards to this sort of thing?

Maybe I'm going about this the wrong way. Is there some sort of best practice when it comes to something like this?

like image 994
Kelly Nicholes Avatar asked Aug 16 '11 14:08

Kelly Nicholes


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 {% include %} does in Django?

From the documentation: {% extends variable %} uses the value of variable. If the variable evaluates to a string, Django will use that string as the name of the parent template. If the variable evaluates to a Template object, Django will use that object as the parent template.

When {% extends %} is used for inheriting a template?

extends tag is used for inheritance of templates in django. One needs to repeat the same code again and again. Using extends we can inherit templates as well as variables.


1 Answers

if you want to stay DRY, use an include.

{% if foo %}   {% with a as b %}     {% include "snipet.html" %}   {% endwith %}  {% else %}   {% with bar as b %}     {% include "snipet.html" %}   {% endwith %}  {% endif %} 

or, even better would be to write a method on the model that encapsulates the core logic:

def Patient(models.Model):     ....     def get_legally_responsible_party(self):        if self.age > 18:           return self        else:           return self.parent 

Then in the template:

{% with patient.get_legally_responsible_party as p %}   Do html stuff {% endwith %}  

Then in the future, if the logic for who is legally responsible changes you have a single place to change the logic -- far more DRY than having to change if statements in a dozen templates.

like image 169
Ted Avatar answered Oct 21 '22 23:10

Ted