Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
307 views
in Technique[技术] by (71.8m points)

python - Style active navigation element with a Flask/Jinja2 macro

I am using Flask/Jinja2 and Bootstrap 3.

I'd like to add class="active" to the current navigation element.

Those elements are stored in prog_ids:

/programme/23022014
/programme/24022014
/programme/25022014

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 .

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...