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?
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.
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.
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.
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.
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