Flask:请求变量中的当前页面

atp*_*atp 57 jinja2 flask

在模板中,如何获取我当前所在的页面?我宁愿不传递变量page,特别是当我知道有些request.xxx可以提供我的信息时.

<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> 
Run Code Online (Sandbox Code Playgroud)

小智 63

只要您已导入request,就request.path应包含此信息.

  • 请注意,其他变量不适用.它的工作原理是因为`request`是变量之一[默认插入](http://flask.readthedocs.org/en/latest/templating/#standard-context)到模板上下文中. (4认同)

小智 47

在您的应用程序中从flask首先导入请求.然后你可以使用它而不传递给模板:

<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>
Run Code Online (Sandbox Code Playgroud)

  • `request` 导入(到 `*.py` 文件中),仍然出现错误:jinja2.exceptions.UndefinedError: 'request' is undefined (2认同)

小智 45

使用request.path似乎不是一种正确的方法,因为在更改URL规则或在子文件夹下部署站点时,您必须更新路径.

请改用request.url_rule.endpoint,它包含独立于实际路径的实际端点名称:

(Pdb) request.url_rule.endpoint
'myblueprint.client_pipeline'
Run Code Online (Sandbox Code Playgroud)

在模板中:

<li {% if request.url_rule.endpoint == "myblueprint.client_pipeline" %}class="active"{% endif %}>Home</li>
Run Code Online (Sandbox Code Playgroud)

祝好运!

  • 这是正确的答案.其他人使用硬编码路径,这是一个非常糟糕的主意. (5认同)
  • 这仅适用于您在页面的每个部分使用一条路由。否则,这将不是您想要的。= \ (2认同)

小智 6

为了避免使用硬编码的URL,可以使用如下url_for函数:

{% 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 %}
Run Code Online (Sandbox Code Playgroud)

在这种情况下,索引foo,bar和baz将是函数名称,在python代码中使用如下:

@app.route('/')
def index():
Run Code Online (Sandbox Code Playgroud)


iCh*_*hux 5

尝试

<li {% if request.endpoint == "blueprintname.routename" %}class="active"{% endif %}>Home</li>
Run Code Online (Sandbox Code Playgroud)

这对我有用。