Jinja - 是否有任何内置变量来获取当前的HTML页面名称?

hrs*_*ono 18 html python templates jinja2

我对Jinja和Flask很新

我想在导航栏中设置不同的背景颜色以指示当前页面.

是否有任何内置的Jinja变量或方法返回当前的HTML页面?如果可能,我希望代码不需要与Python文件通信.

所以,如果我现在在index.html,它将返回"index"或"index.html"

这是我模板中的导航代码:

<ul>
   {% for item in navigation %}
       <a href="{{url_for(item.route)}}">
       <li>
           {{item.text}}
       </li>
       </a>
   {% endfor %}
</ul>
Run Code Online (Sandbox Code Playgroud)

我想添加if语句,以便在当前页面会得到<li>class

{% if ??? %}
   <li class="current">
   ...
   </li>
{% else %}
   ...
{% endif %}
Run Code Online (Sandbox Code Playgroud)

谢谢

hda*_*ang 33

jinja2文档中有一个针对您的问题的技巧:http://jinja.pocoo.org/docs/tricks/

如果你的列表很简单,只需使用请求对象,就像这样:

<li {% if request.endpoint == item.endpoint %} class='active' {% endif %}>
    <a href="{{url_for(endpoint)}}">{{item.text}}</a>
</li> 
Run Code Online (Sandbox Code Playgroud)

通常,我将此代码段写入一个带有显式参数的宏active:

{% macro render_sitem(endpoint, display, cls='', icon-cls='', active='') %}
<li {% if request.endpoint == endpoint or active == endpoint %} class='active' {% endif %}>
    <a class='{{cls}}' href="{{url_for(endpoint)}}"><i class="{{icon-cls}}"></i> {{display}}</a>
</li>
{% endmacro %}
Run Code Online (Sandbox Code Playgroud)

列表将是这样的:

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

因此,如果您有一个扩展或包含您的列表的子页面,您可以设置活动项目,如:

{% set active_page = 'page.index' %} 
Run Code Online (Sandbox Code Playgroud)

在您的子页面的顶部.


Che*_*ara 5

在金字塔1.5中,没有像Flask中的request.endpoint这样的方法.

我们使用自定义过滤器get_endpoint

Request的| get_endpoint

jinja2_custom_filters.py:

from pyramid_jinja2 import Environment

def get_endpoint(str):
    """

    :param str:
    :return:
    """
    return str.split('/')[-1]


env = Environment()
env.filters['get_endpoint'] = get_endpoint
Run Code Online (Sandbox Code Playgroud)

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

也许对某人有用:)