Search code examples
htmltemplatesflaskjinja2sidebar

Jinja modify base.html depending on the page


I'm using jinja in the templates of my flask project.

My question is : how to change the color of one of the elements of the sidebar (which is in base.html file) when you are on the corresponding page ?

I mean let's say I have a sidebar with the following titles linked to their corresponding page : dashboard, feature1, feature2.

How can I do if I want feature1 to change of color when I am on feature1, then change back feature1 to its original color and turn dashboard to the selected color when I click and go on dashboard page ?

Because I don't really know how to simply do it instead of creating a new content in each of my pages' html template.

Thanks in advance !


Solution

  • You can use a CSS class for the active link. This defines the style properties for the menu entry of the currently used page.

    .active {
        background-color: red;
    }
    

    To add the class to the menu item, you can use a simple if condition using the request object. Here you can compare whether the current request is the same as the identifier of the endpoint.

    @app.route('/')
    def dashboard():
        # ...
    
    <a 
        class="{% if request.endpoint == 'dashboard' %}active{% endif %}" 
        href="{{ url_for('dashboard') }}"
    >Dashboard</a>