pythonclasstwitter-bootstrapflaskjinja2

Changing the active class of a link with the twitter bootstrap css in python/flask


I got the following html snippet from my page template.html.

<ul class='nav'>
    <li class="active"><a href='/'>Home</a></li>
    <li><a href='/lorem'>Lorem</a></li>

    {% if session['logged_in'] %}
        <li><a href="/account">Account</a></li>
        <li><a href="/projects">Projects</a>
        <li><a href="/logout">Logout</a></li>
    {% endif %}

    {% if not session['logged_in'] %}
        <li><a href="/login">Login</a></li>
        <li><a href="/register">Register</a></li>
    {% endif %}
</ul>

As you can see on line 2, there's the class active. This highlights the active tab with the twitter bootstrap css file. Now, this will work fine if I would visit www.page.com/ but not when I would visit www.page.com/login for example. It would still highlight the home link as the active tab.

Of course, I could easily do this with Javascript/jQuery but I'd rather not use that in this situation.

There's already a working solution for ruby on rails but I don't know how to convert that into python/jinja (I'm rather new to jinja/flask, never worked with ruby at all)


Solution

  • Have you looked at this ? https://jinja.palletsprojects.com/en/3.1.x/tricks/#highlighting-active-menu-items

    Highlighting Active Menu Items

    Often you want to have a navigation bar with an active navigation item. This is really simple to achieve. Because assignments outside of blocks in child templates are global and executed before the layout template is evaluated it’s possible to define the active menu item in the child template:

    {% extends "layout.html" %}
    {% set active_page = "index" %}
    

    The layout template can then access active_page. Additionally it makes sense to define a default for that variable:

    {% set navigation_bar = [
        ('/', 'index', 'Index'),
        ('/downloads/', 'downloads', 'Downloads'),
        ('/about/', 'about', 'About')
    ] -%}
    
    {% set active_page = active_page|default('index') -%}
    ...
    <ul id="navigation">
        {% for href, id, caption in navigation_bar %}
        <li{% if id == active_page %} class="active"{% endif
        %}><a href="{{ href|e }}">{{ caption|e }}</a>
        </li>
    {% endfor %}
    </ul>