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
Jinja, also commonly referred to as "Jinja2" to specify the newest release version, is a Python template engine used to create HTML, XML or other markup formats that are returned to the user via an HTTP response.
Jinja2 is a full-featured template engine for Python. It has full unicode support, an optional integrated sandboxed execution environment, widely used and BSD licensed.
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.
In pyramid 1.5 there are no method like request.endpoint in Flask.
We use custom filter get_endpoint
request.path|get_endpoint
jinja2_custom_filters.py:
from pyramid_jinja2 import Environment def get_endpoint(str): """ :param str: :return: """ return str.split('/')[-1] env = Environment() env.filters['get_endpoint'] = get_endpoint
and in development.ini:
jinja2.filters = model_url = pyramid_jinja2.filters:model_url_filter route_url = pyramid_jinja2.filters:route_url_filter static_url = pyramid_jinja2.filters:static_url_filter get_endpoint = path to ... jinja2_custom_filters.get_endpoint
Maybe it will be useful to someone :)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With