Jinja - Is there any built-in variable to get current HTML page name?

后端 未结 2 1683
迷失自我
迷失自我 2020-12-24 07:56

i\'m very new to Jinja and Flask

I want to set different background color in the navigation bar to indicate the current page.

Is there any built-in Jinja var

相关标签:
2条回答
  • 2020-12-24 08:30

    There is a trick in jinja2 document for your problem: http://jinja.pocoo.org/docs/tricks/

    If your list is simple enough, just using request object, something like that:

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

    Normally, I write this snippet to a macro with an explicit argument to set 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 %}
    

    The list will be something like:

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

    So if you have a child page which extends or includes your list, you can set active item like:

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

    in the top of your child page.

    0 讨论(0)
  • 2020-12-24 08:34

    In pyramid 1.5 there are no method like request.endpoint in Flask.

    We use custom filter 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
    

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

    Maybe it will be useful to someone :)

    0 讨论(0)
提交回复
热议问题