Search code examples
djangodjango-templatesdjango-viewsglobal-variablesinclusion

Django dynamic menu in global view (base.html) to be visible in all templates


I have built the website with couple templates but I would like to achieve how to read menu from DB in the base.html that would be visible on entire website, I dont want to add it to every template. I found in the docs by POLL example:

https://docs.djangoproject.com/en/dev/howto/custom-template-tags/#inclusion-tags

Screenshots of the error

TemplateSyntaxError at / Invalid block tag: 'show_menu'

Template Syntax Error

Base.html Error

Under app I did: templatetags/menu.py

from django import template
register = template.Library()

@register.inclusion_tag('menu.html')
def show_menu(menu):
    menu = Menu.objects.all()
    return {'menu': menu}

base.html

{% load menu %}
<!DOCTYPE html>
<html lang="en">
<head></head>
<body>
    {% show_menu menu %}
    {% block content %}{% endblock %}
</body>
</html>

index.html

{% extends "base.html" %}

{% block content %}
Hello World! (Content)
{% endblock %}

Please help, what I am doing wrong? Thanks


Solution

  • You don't seem to have actually read that documentation page you link to. Firstly, it gives explicit instructions about where to put the template tag code: not in view.py, but in a new file inside a templatetags directory inside your app.

    Secondly, that page also explains that you need to load each tag library you use inside each template that uses them: so assuming that you've put your tag into templatetags/menu.py, you would do {% load menu %}.