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?


Solution 1:

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.

Solution 2:

Like this:

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

If the html is too big and you don't want to repeat it, then the logic would better be placed in the view. You set this variable and pass it to the template's context:

p = (age > 18 && patient) or patient.parent

and then just use {{ p }} in the template.