Django tip: Variable aliasing using {% with %} tags

Say you have an include that loops over a list like this…

  # render_customers.html

  {% for c in customers %}
    {{ c.first_name }}
  {% endfor %}

That is, it loops over a list called customers and only a list called customers. Now say you want to use it multiple times in your template with different lists – e.g. one called new_customers and another called old_customers – then you’d do it like this…

{% with new_customers as customers %}
  {% include "render_customers.html" %}
{% endwith %}

{% with old_customers as customers %}
  {% include "render_customers.html" %}
{% endwith %}

A simple trick but one that I don’t believe is clearly laid out in the otherwise fantastic Django documentation. Here’s what the blurb for the {% with %} tag says in the docs: “Caches a complex variable under a simpler name. This is useful when accessing an “expensive” method (e.g., one that hits the database) multiple times.”

I didn’t understand the purpose of the tag until I came across a one-line mention of it in the reusable form templates section.

Hope it helps.


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s