K
K
Kozlov2019-12-13 05:24:13
Flask
Kozlov, 2019-12-13 05:24:13

What other ways are there to put class active on a template in flask?

I'm learning Flask. I'm making a test site using templates. Site menu in base.html. When you go to a specific page, the active link is highlighted, it is given the active class. So far I've found a solution like this:

<li {% if request.path == '/' %}class="active"{% endif %}>
     <a href="/">Главная</a>
</li>

Is this correct, and are there any other options on how to assign the active class to an active link when using templates?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Andrew, 2019-12-13
@romandkoz

It is possible like this:

spoiler
<ul class="nav navbar-nav navbar-right">
    <li {{ home_active }}><a href="/">Home</a></li>
    <li {{ places_active }}><a href="/places">Places</a></li> 
</ul>

@app.route('/')
@app.route('/home')
def index():
    return render_template('index.html', home_active="class=active")

@app.route('/places')
def map():
    return render_template('places.html', places_active="class=active")

Or like this:
spoiler
def some_view():
    return render_template('template.html', active='home')

<li class="{% if active=='home' %}active{%endif %}">Home</li>
<li class="{% if active=='blog' %}active{%endif %}">Blog</li>

Highlighting Active Menu Items
jinja.pocoo.org/docs/tricks
https://jinja.palletsprojects.com/en/2.10.x/tricks/
{% extends "layout.html" %}
{% set active_page = "index" %}

{% set navigation_bar = [
    ('/', 'index', 'Index'),
    ('/downloads/', 'downloads', 'Downloads'),
    ('/about/', 'about', 'About')
] -%}
{% set active_page = active_page|default('index') -%}
...
<ul id="navigation">
{% for href, id, caption in navigation_bar %}
  <li{% if id == active_page %} class="active"{% endif
  %}><a href="{{ href|e }}">{{ caption|e }}</a></li>
{% endfor %}
</ul>

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question