Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flask: current page in request variable

Tags:

flask

jinja2

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> 
like image 999
atp Avatar asked Dec 30 '11 05:12

atp


3 Answers

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

like image 124
ranksrejoined Avatar answered Oct 26 '22 07:10

ranksrejoined


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!

like image 61
negus Avatar answered Oct 26 '22 07:10

negus


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>
like image 50
Sosiska Avatar answered Oct 26 '22 08:10

Sosiska