Search code examples
djangohtmldjango-templatesdjango-context

Change to my left nav bar when on a certain page?


Maybe I'm going about this all the wrong way... But what I'm trying to do is change the left navigation by what page I'm on. The left nav in base.html is apparent throughout, but once the user is on forums.html (extends base.html), I wanted to have the left navigation change.

base.html:

{% if not no_left_bar %}
    <div class="container">
        <div class="row">
        <!-- Left Side Bar -->
             <nav>
                  original base.html nav goes here
             </nav>
             <!-- Some condition that goes here/ When forums.html -->
             <nav>
                  forums.html( extends base.html ) nav goes here
             </nav>
         </div>
     </div>
{% endif %}

I don't know if I have to pass it through base context or not. I appreciate the help and any idea's/ recommendations.


Solution

  • The django {% block %} template tag lets you define blocks of content that can be overridden by child templates. Try something like this:

    base.html

    <div class="container">
        <div class="row">
            {% block nav %}
                 <nav>
                      <!-- original base.html nav goes here -->
                 </nav>
             {% endblock %}
         </div>
     </div>
    

    and then in forums.html

    {% extends "base.html" %}
    
    {% block nav %}
    
        <nav>
            <!-- new forums.html nav goes here -->
        </nav>
    
    {% endblock %}
    

    The output will look like

    <div class="container">
        <div class="row">
                <nav>
                    <!-- new forums.html nav goes here -->
                </nav>
         </div>
     </div>
    

    Documentation here: https://docs.djangoproject.com/en/dev/topics/templates/#template-inheritance