Jinja - 有没有内置的变量来获取当前的HTML页面名称? [英] Jinja - Is there any built-in variable to get current HTML page name?
问题描述
我对Jinja和Flask很新颖
i'm very new to Jinja and Flask
我想在导航栏中设置不同的背景颜色来表示当前页面。
I want to set different background color in the navigation bar to indicate the current page.
是否有任何内置Jinja变量或方法返回当前HTML页面?如果可能,我希望代码不需要与Python文件进行通信。
Is there any built-in Jinja variable or method that returns current HTML pages? If possible, I want the code that doesn't need to communicate with the Python file.
所以如果我目前在 index.html
,它会返回index或index.html。
So if i'm currently in index.html
, it will return "index" or "index.html"
以下是我的模板中的导航代码:
Here's my navigation code in my template:
<ul>
{% for item in navigation %}
<a href="{{url_for(item.route)}}">
<li>
{{item.text}}
</li>
</a>
{% endfor %}
</ul>
如果语句,我想添加当前页面将得到
< li>
,其中 class
{% if ??? %}
<li class="current">
...
</li>
{% else %}
...
{% endif %}
谢谢
Thank You
推荐答案
jinja2文件中有一个技巧可以解决您的问题: http://jinja.pocoo.org/docs/tricks/
There is a trick in jinja2 document for your problem: http://jinja.pocoo.org/docs/tricks/
如果你的列表很简单,只需要使用request对象,如下所示:
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 %}
该列表将如下所示:
<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' %}
位于您的子页面顶部。
这篇关于Jinja - 有没有内置的变量来获取当前的HTML页面名称?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!