Flask: current page in request variable

FlaskJinja2

Flask Problem Overview


In a template, how do I get what page I'm currently on? I'd rather not pass a variable like page , especially when I know some request.xxx can provide me with the information.

<li {% if page=="home" %}class="active"{% endif %}>                   
    <a href="/">Home</a>                                                
</li>                                                                 
<li {% if page=="about" %}class="active"{% endif %}>                  
    <a href="/about">About</a>                                          
</li> 

Flask Solutions


Solution 1 - Flask

As long as you've imported request, request.path should contain this information.

Solution 2 - Flask

Using request.path doesn't seem to be a proper approach since you'll have to update the paths in case of changing URL rules or deploying your site under a subfolder.

Use request.url_rule.endpoint instead, it contains actual endpoint name independent of actual path:

(Pdb) request.url_rule.endpoint
'myblueprint.client_pipeline'

In a template:

<li {% if request.url_rule.endpoint == "myblueprint.client_pipeline" %}class="active"{% endif %}>Home</li>

Good luck!

Solution 3 - Flask

First import request from flask in your application. Then you can use it without passing to template:

<li {%- if request.path == "/home" %} class="active"{% endif %}>
    <a href="/">Home</a>
</li>
<li {%- if request.path=="/about" %} class="active"{% endif %}>
    <a href="/about">About</a>
</li>

Solution 4 - Flask

To avoid using hard-coded URLs you can use the url_for function like this:

{% for ni in ['index', 'foo', 'bar', 'baz'] %}
<li {%- if request.path == url_for(ni) %} class="active"{% endif %}><a href="{{ url_for(ni) }}">{{ ni | capitalize }}</a></li>
{% endfor %}

In this case index, foo, bar and baz would be function names, used like this in your python code:

@app.route('/')
def index():

Solution 5 - Flask

Try

<li {% if request.endpoint == "blueprintname.routename" %}class="active"{% endif %}>Home</li>

This one worked for me.

Solution 6 - Flask

You can also use .split if your url has more stuff in it.

Example:

/product
/product/add
/product/32432/edit
/product/32432/view

{{ request.path.split('/')[1] }}

This will return only "product"

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionatpView Question on Stackoverflow
Solution 1 - FlaskranksrejoinedView Answer on Stackoverflow
Solution 2 - FlasknegusView Answer on Stackoverflow
Solution 3 - FlaskSosiskaView Answer on Stackoverflow
Solution 4 - FlaskMoepManView Answer on Stackoverflow
Solution 5 - FlaskiChuxView Answer on Stackoverflow
Solution 6 - FlaskIaronView Answer on Stackoverflow