Qty: current page in query variable

In the template, how do I get which page I'm on now? I would prefer not to pass a variable like page , especially when I know that request.xxx can provide me with 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> 
+57
flask jinja2
Dec 30 '11 at 5:30
source share
6 answers

While you have imported request , request.path should contain this information.

+62
Dec 30 2018-11-11T00:
source share

The first import request from a flask in your application. Then you can use it without going to the 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> 
+46
Jan 03 '12 at 16:59
source share

Using request.path does not seem to be the right approach, as you will have to update the paths if you change the URL rules or deploy your site under a subfolder.

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

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

In the template:

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

Good luck

+45
Jul 29 '14 at 10:27
source share

To avoid using hard-coded URLs, you can use the url_for function as follows:

 {% 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 will be the names of the functions that are used in your python code:

 @app.route('/') def index(): 
+6
Mar 14 '16 at 11:18
source share

Try

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

This worked for me.

+3
Jul 16 '15 at 10:44
source share

You can also use .split if there is anything else in your url.

Example:

/
product / product / add
/ Product / 32432 / edit
/ Product / 32 432 / view

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

This will return only the "product"

0
Sep 01 '19 at 8:57
source share



All Articles