skip to Main Content

i want to have the current page (on which the user is currently on) link to have a different color than the other page links, so user knows which page they are on. using this on python flask.

this is part of my layout.html

<ul class="nav">
     <li {% if request.path == '/' %} class="active"{% endif %}><a href="{{ url_for('index') }}">Home</a></li>
     <li {% if request.path == url_for('browse') %} class="active"{% endif %}><a href="{{ url_for('browse') }}">Browse</a></li>
     <li {% if request.path == url_for('details') %} class="active"{% endif %}><a href="{{ url_for('details') }}">Details</a></li>
     <li {% if request.path == url_for('profile') %} class="active"{% endif %}><a href="{{ url_for('profile') }}">Profile <img src="{{ url_for('static', filename='assets/images/profile-header.jpg') }}" alt=""></a></li>
     <!-- Add more items as required -->
</ul>
                    

This is my app.py

from flask import Flask, render_template, request

app = Flask(__name__)

@app.route('/')
def index():
    return render_template('index.html', request=request)

@app.route('/browse')
def browse():
    return render_template('browse.html', request=request)

@app.route('/details')
def details():
    return render_template('details.html', request=request)

@app.route('/profile')
def profile():
    return render_template('profile.html', request=request)

if __name__ == '__main__':
    app.run()

i have used {% if request.path == url_for(‘browse’) %} class="active"{% endif %}>%} but failed

2

Answers


  1. Chosen as BEST ANSWER

    NVM I figured it out, used javaScript and fixed it, here's the solution

    <script>
    // Get the current page URL path
     var currentPath = window.location.pathname;
                    
    // Get the menu item with a matching URL and add the "active" class
     if (currentPath === "{{ url_for('index') }}") {
      document.getElementById("home").classList.add("active");
      } else if (currentPath === "{{ url_for('browse') }}") {
      document.getElementById("browse").classList.add("active");
      } else if (currentPath === "{{ url_for('details') }}") {
       document.getElementById("details").classList.add("active");
      } else if (currentPath === "{{ url_for('profile') }}") {
               document.getElementById("profile").classList.add("active");
      }
    </script>
    

  2. it seems like all of your class names are the same "active", so i dont see how can you change your css if you dont change your class names. All if statements refers to same class, so you can create different classes in your css file and refer them in your if statements.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search