Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
312 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 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...