1

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

Radek
  • 1,149
  • 2
  • 19
  • 40

1 Answers1

3

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 %}.

Daniel Roseman
  • 588,541
  • 66
  • 880
  • 895
  • I edited the code, as above I created folder TEMPLATETAGS under app and put MENU.PY file with the code. Then I did in the template: {% load menu %}, now I got this error: menu' is not a valid tag library: Template library menu not found, tried django.templatetags.menu,django.contrib.staticfiles.templatetags.menu,django_admin_bootstrapped.templatetags.menu,django.contrib.admin.templatetags.menu, http://cl.ly/image/3J0t3N061e12 – Radek Mar 31 '13 at 20:04
  • I found the problem by adding the "__init__.py" under the templatetags directory. Now I am having problem that "global name 'Menu' is not defined", if I add the from django.db import models from models import Menu, it will throw an error: "'menu' is not a valid tag library: ImportError raised loading ng.templatetags.menu: No module named models" – Radek Mar 31 '13 at 20:22
  • 1
    Why would you import the models from `django.db`? They're in your app, wherever that is. `from myapp.models import Menu`. – Daniel Roseman Mar 31 '13 at 20:47