Python – Jinja – Is there any built-in variable to get current HTML page name

html, jinja2, python, templates

i'm very new to Jinja and Flask

I want to set different background color in the navigation bar to indicate the current page.

Is there any built-in Jinja variable or method that returns current HTML pages? If possible, I want the code that doesn't need to communicate with the Python file.

So if i'm currently in index.html, it will return "index" or "index.html"

Here's my navigation code in my template:

<ul>   {% for item in navigation %}       <a href="{{url_for(item.route)}}">       <li>           {{item.text}}       </li>       </a>   {% endfor %}</ul>

I want to add if statement so the current page will get <li> that has class

{% if ??? %}   <li class="current">   ...   </li>{% else %}   ...{% endif %}

Thank You

Best Solution

There is a trick in jinja2 document for your problem: http://jinja.pocoo.org/docs/tricks/

If your list is simple enough, just using request object, something like that:

<li {% if request.endpoint == item.endpoint %} class='active' {% endif %}>    <a href="{{url_for(endpoint)}}">{{item.text}}</a></li> 

Normally, I write this snippet to a macro with an explicit argument to set active:

{% macro render_sitem(endpoint, display, cls='', icon-cls='', active='') %}<li {% if request.endpoint == endpoint or active == endpoint %} class='active' {% endif %}>    <a class='{{cls}}' href="{{url_for(endpoint)}}"><i class="{{icon-cls}}"></i> {{display}}</a></li>{% endmacro %}

The list will be something like:

 <ul class="nav nav-list">     {{render_sitem('page.index',  _('Pages'), icon-cls='icon-sitemap', active=active_page)}}     {{render_sitem('post.index', _('Posts'), icon-cls='icon-file', active=active_page)}}     {{render_sitem('user.index', _('Users'), icon-cls='icon-group', active=active_page)}} </ul>

So if you have a child page which extends or includes your list, you can set active item like:

{% set active_page = 'page.index' %} 

in the top of your child page.