【问题标题】:Jinja - Is there any built-in variable to get current HTML page name?Jinja - 是否有任何内置变量来获取当前 HTML 页面名称?
【发布时间】:2012-07-24 19:25:53
【问题描述】:

我对 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>

我想添加 if 语句,以便当前页面将获得具有 class&lt;li&gt;

{% if ??? %}
   <li class="current">
   ...
   </li>
{% else %}
   ...
{% endif %}

谢谢

【问题讨论】:

标签: python html templates jinja2


【解决方案1】:

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> 

通常,我将此 sn-p 写入一个带有显式参数的宏以设置 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 %}

列表将类似于:

 <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>

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

{% set active_page = 'page.index' %} 

在您的子页面顶部。

【讨论】:

    【解决方案2】:

    在金字塔 1.5 中,Flask 中没有类似 request.endpoint 的方法。

    我们使用自定义过滤器get_endpoint

    request.path|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
    

    在 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
    

    也许它对某人有用:)

    【讨论】:

      【解决方案3】:

      在 Flask 2.0.1 中,request 对象在模板中可用。有了这个,您可以轻松地使用它来使用request.path 属性检查页面。

      检查示例如下:

      {% if request.path == "/" %}
        <h1>You are at the root</h1>
      {% endif %}
      

      【讨论】:

        猜你喜欢
        • 2016-12-18
        • 2013-11-03
        • 1970-01-01
        • 2011-06-17
        • 1970-01-01
        • 2012-01-06
        • 1970-01-01
        • 1970-01-01
        • 2019-04-06
        相关资源
        最近更新 更多