sumpen
sumpen

Reputation: 541

Include a menu to several templates in Django

I'm trying NOT to write same code twice on different templates. Real hassle when changing something.

So when I go to a section of the webpage, I want to display a side menu. This side-menu is suppose to be on several templates. Like index.html, detail.html, manage.html and so on.

But the section is only a part of the webpage, so I can't have it in base.html.

I was thinking about using include. But since the side menu is dependent of DB queries to be generated, I then have to do queries for each view. Which also makes redundant code.

What is best practice for this feature?

Cheers!

Upvotes: 1

Views: 391

Answers (1)

Aamir Rind
Aamir Rind

Reputation: 39649

You could write custom inclusion_tag, that's more feasible for the scenario:

my_app/templatetags/my_app_tags.py

from django import template

register = template.Library()

@register.inclusion_tag('side_menu.html')
def side_menu(*args, **kwargs):
    # prepare context here for `side_menu.html`
    ctx = {}
    return ctx

Then in any template you want to include side menu do this:

{% load side_menu from my_app_tags %}

{% side_menu %}

Upvotes: 5

Related Questions