Login

Simple DRY Tabs using Django 1.3

Author:
Voightkampff
Posted:
April 28, 2011
Language:
HTML/template
Version:
1.3
Score:
3 (after 6 ratings)

I was just playing around with Django 1.3 and came across the new 'with' addition to the include tag. I thought this was a super elegant way to implement a DRY tab menu without having to move menu code into the views. Enjoy!

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
**Placed in templates/includes/tabs.html**

<ul class="tab-menu">
    <li class="{% if active_tab == 'tab1' %} active{% endif %}"><a href="#">Tab 1</a></li>
    <li class="{% if active_tab == 'tab2' %} active{% endif %}"><a href="#">Tab 2</a></li>
    <li class="{% if active_tab == 'tab3' %} active{% endif %}"><a href="#">Tab 3</a></li>
</ul>



**Placed in your page template**

{% include "includes/tabs.html" with active_tab='tab1' %}

More like this

  1. Bootstrap Accordian by Netplay4 5 years, 11 months ago
  2. Bootstrap theme for django-endless-pagination? by se210 8 years, 11 months ago
  3. Bootstrap theme for django-endless-pagination? by se210 8 years, 11 months ago
  4. Reusable form template with generic view by roldandvg 9 years ago
  5. Pagination Django with Boostrap by guilegarcia 9 years, 2 months ago

Comments

cferreir (on August 5, 2011):

Thanks for sharing. This was very helpful. Finally got my navigation working where it supports multiple/nested menu levels and shows which ones are active.

#

sergzach (on March 26, 2012):

Thank you! When I created a snippet #2722 I did not take into account the option with of inclusion tag.

I think your solution is better.

My decision have only one plus (your have several ones). In case of #2722 inheritance is possible. Sometimes it is more convenient and conceptual than inclusion.

#

sergzach (on March 26, 2012):

And one more plus in #2722. In your case if you want to mek whole fragment different (not only class attribute) you should write several times very similar code for each option. But I would like DRY menu.

#

sergzach (on March 27, 2012):

Now I use your snippet instead of mine. Thanks a lot!

#

ccarnell (on August 2, 2012):

This is such a clean solution; thank you so much for taking the time to share this!

#

jnns (on June 18, 2013):

Thanks for this, I didn't know about {% include with %}. This is great!

#

Please login first before commenting.