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

Kelly Nicholes picture Kelly Nicholes · Aug 16, 2011 · Viewed 139.2k times · Source

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?

Answer

Ted picture Ted · Aug 16, 2011

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.