Jinja - Is There Any Built-in Variable To Get Current Html Page Name?
Solution 1:
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 {% ifrequest.endpoint == item.endpoint %} class='active' {% endif %}><ahref="{{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 %}>
<aclass='{{cls}}'href="{{url_for(endpoint)}}"><iclass="{{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.
Solution 2:
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
defget_endpoint(str):
"""
:param str:
:return:
"""returnstr.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 :)
Solution 3:
In Flask 2.0.1, the request
object is available in the template. With this you can easily use it to check the page using the request.path
attribute.
An example of a check would be like this:
{% if request.path == "/" %}
<h1>You are at the root</h1>
{% endif %}
Post a Comment for "Jinja - Is There Any Built-in Variable To Get Current Html Page Name?"