2

I was wondering if it's possible to generate a nav bar. My idea was to get a list of sorts from urls.py and use a {% for %} block to ieterate through and create the navbar in the template. Any suggestions on how I could go about implementing this strategy, or if there's a better strategy?

Brian Lee
  • 305
  • 4
  • 14

1 Answers1

1

Not sure how you want to go about constructing your list of navigation items... Per @Doug's suggestion in the comments, you can see this question for how to dynamically build a list of available routes.

As for creating your navigation bar, you could very simply create a template for just the navigation bar and then include it in your main template.

Navigation template

<!-- navigation.html.j2 -->
<nav>
    <ul class="nav-items">
        {% for nav_item in nav_list %}
            <li>{{nav_item}}</li>
        {% end for %}
    </ul>
</nav>

Main template

<!-- main.html.j2 -->
<!DOCTYPE html>
<html>
    <head>
        ...
    </head>
    <body>
        {% include "navigation.html" %}
        <main>
            {% block content %}{% endblock %}
        </main>
    </body>
</html>
ngoue
  • 1,045
  • 1
  • 12
  • 25
  • but where does that nav_list come from? He wants a navbar of all of his urls that are in his urls.py file, how does he get them inside that list? – Gabriel Belini Jun 21 '17 at 16:31
  • @gabrielbelini hence my comment "Not sure how you want to go about constructing your list of navigation items..." – ngoue Jun 21 '17 at 16:33
  • didn't see that at first, sorry. – Gabriel Belini Jun 21 '17 at 16:35
  • There are a couple options... you could look at dynamically building the list (a lot of work... I'll see if I can find my previous answer on how to do this), or you can keep a static list that you manually update when you want to... this is typically the better option, since a dynamic list is hard to control / scale / plan for when doing UI designs.... edit: here's the link for thread on dynamically getting all of the urls / views: https://stackoverflow.com/questions/32933229/how-to-get-a-list-of-all-views-in-a-django-application/35760156#35760156 – Douglas Jun 21 '17 at 17:16