1

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.

4

3 に答える 3

1

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.

于 2013-11-13T12:17:35.407 に答える
0

This is how I do it:

in my _mainlayout

 {% block stylesheets %}
    Links to stylesheets go here
 {% endblock %}

 {% block main_body_area %}
        Replace with your html body
 {% endblock %}

 {% block scripts %}
    Add js scripts here
 {% endblock %}

Then in the child templates simply do the following:

{% extends "_mainlayout.html" %}

 {% block stylesheets %}   
    <style sheets go here/>
 {% endblock %}

 {% block main_body_area %}
    <your page content here/>
 {% endblock %}

 {% block scripts %}
    add any js scripts here
 {% endblock %}

You can then add your active_page in the head section which in the example I gave you is where I keep the stylesheets. I do it this way because in my _mainlayout file I have a standard css stylesheet which is used across all pages and then if I need additional page specific layouts I include it in that particular page if not just leave it blank.

The same goes with the js files I don't want to load scripts on pages that dont need them so it makes it easy to include them on pages that do require specific js files.

于 2013-01-18T13:18:37.473 に答える
0

I just had the same issue in Jinja2 version 2.8. Upgrading it to version 2.9 solved the problem.

于 2017-05-31T01:03:24.820 に答える