alufers
alufers

Reputation: 134

How to make a menu in a Base Template(Django)?

How can I make a menu in Django that is in the base template and it get's it's content from the database? My base template:

<!DOCTYPE html>
<html>
    <head>
        <title>{% block title %}My page{% endblock %}</title>
        <link rel="stylesheet" href="{{ STATIC_URL }}css/uikit.min.css" />
        <script src="{{ STATIC_URL }}js/jquery.min.js"></script>
        <script src="{{ STATIC_URL }}js/uikit.min.js"></script>
    </head>
    <body>
        {% block content %}
        {% endblock %}
    </body>
</html>

PS:Sorry for my English, I'am polish.

Upvotes: 0

Views: 3290

Answers (2)

petkostas
petkostas

Reputation: 7460

Back sometime I had the same question, I ended up creating a Mixin and injecting the menu in there, more specific (this is in the case you are using Class Based View...which you should...):

class MenuMixin(object):
    def get_context_data(self, **kwargs):
        context = super(MenuMixin, self).get_context_data(**kwargs)
        context['menu'] = MenuModel.objects.all()
        return context


class MyListView(MenuMixin, ListView):
    ...

Then in your templates you can simply:

{% include "partials/menu.html" %}

And inside your partials/menu.html:

{% for item in menu %}
    <a href="{{ item.link }}">{{ item.name }}</a>
{% empty %}
    Do something for empty...
{% endfor %}

Upvotes: 2

mariodev
mariodev

Reputation: 15559

You might be insterested in django-simple-menu.

Then to adapt it to your use case, you can simply read the database items from inside menus.py like so (keep in mind this is just a pseudo-code):

# menus.py

items = Menu.objects.all()

for item in items:
    Menu.add_item("main", MenuItem(item.name, item.url),
                          weight=10,
                          icon=item.name.lower()))

Other solutions you may think of is to create context processor or custom tag, but those may be difficult to figure out on your own if you're less experienced and the menu structure is more complicated (sub-menus).

Upvotes: 1

Related Questions