使用 Flask/Jinja2 宏设置活动导航元素的样式 [英] Style active navigation element with a Flask/Jinja2 macro
问题描述
我正在使用 Flask/Jinja2 和 Bootstrap 3.
I am using Flask/Jinja2 and Bootstrap 3.
我想将 class="active"
添加到当前导航元素.
I'd like to add class="active"
to the current navigation element.
那些元素存储在 prog_ids
中:
Those elements are stored in prog_ids
:
/programme/23022014
/programme/24022014
/programme/25022014
我遵循了一些示例,例如 这个 和我的 HTML 代码是:
I followed some examples like this one and my HTML code is :
<ul class="nav nav-pills ">
{% for prog_id in prog_ids %}
{% macro nav_link(endpoint, prog_id) %}
{% if request.endpoint.endswith(endpoint) %}
<li class="active">
<a href="{{ url_for(endpoint) }}">
<span class="badge pull-right">-</span>
{{prog_id|strftime_b}}
</a>
</li>
{% else %}
<li>
<a href="{{ url_for(endpoint) }}">
<span class="badge pull-right">-</span>
{{prog_id|strftime_b}}
</a>
</li>
{% endif %}
{% endmacro %}
{% endfor %}
</ul>
上面的代码有错误吗?因为,它什么也没显示.
Is there any error in the code above ? Because, it shows nothing .
推荐答案
你的代码只是一遍又一遍地定义一个宏,它不渲染任何东西.避免阅读 request.endpoint
并使用基本模板来做到这一点.
Your code just defines a macro over and over again, it doesn't render anything. Avoid reading request.endpoint
and use base templates to do this.
base.html
<ul class="nav nav-pills">
<li class="{% block nav_here %}{% endblock %}">Here</li>
<li class="{% block nav_there %}{% endblock %}">There</li>
<li class="{% block nav_anywhere %}{% endblock %}">Anywhere</li>
</ul>
{% block content %}{% endblock %}
there.html
{% extends "base.html" %}
{% block nav_there %}active{% endblock %}
{% block content %}
<blockquote>No matter where you go, there you are.</blockquote>
{% endblock %}
基础导航在li
类中定义空的nav_
块,子模板将相关的块设置为active
.您可以将其扩展到您也希望在页面内进行子导航.
The base navigation defines empty nav_
blocks in the li
class and the sub template sets the relevant one to active
. You can extend this as far as you want to have sub-navigation within pages too.
这篇关于使用 Flask/Jinja2 宏设置活动导航元素的样式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!