Search code examples
pythontemplatesflaskjinja2

Jinja active_page not working when within an included file


So i have a working layout _layout.html (using Jinja2 v2.6 and Flask) which is including my header with {% include 'header.html' %} and the body contents with {% block content %}{% endblock %} (in that order).

header.html

<ul>
    <li><a href="/about" {% if active_page == 'about' %} class="selected" {% endif %}>ABOUT</a></li>
</ul>

about.html

{% extends "_layout.html" %}
{% set active_page = 'about' %}

{% block content %}
    ...
{% endblock %}

The problem is that as the child templates are global and executed before the layout template is evaluated so the class="selected" are not being added as the header.html template does not have the active_page in its context.

If i place the header.html contents in the main layout everything works fine, how can i get this to work using the include and structure i have?

EDIT:

I have also tried {% include 'header.html' with context %} and {% from 'header.html' import input with context %} both do not work.


Solution

  • The easiest work around could be to just use JavaScript (JQuery in this case):

    JQuery:

    var currentPage = window.location.pathname;
    
    $('nav ul li a').each(function(){
        if($(this).attr('href') == currentPage){
            $(this).addClass('selected');
        }
    });
    

    This function will add a selected class to the <a> tag that matches the current window location.