Underline element when on page in Navigation Bar

Hey,

I’m looking to underline the element in the navigation bar which corresponds to the page that I’m on.
Example: If I’m on the download page, like the Django website I want it to make the download text in navigation bar darker.

I can do this with normal HTML and CSS but what I’m doing is I have a base.html and I extend that to all my pages. In the base.html I also extend navigationBar.html so it doesn’t look cluttered.

Part of navigation bar:

<a href="#" class="hover:text-portfolio-medium-green">Home</a>

I’m unable to figure out a way out to do it because I’m extending the template and can’t hardcode the color change stuff.

I thought of a if statement but couldn’t think how I would send the page I’m on to the navigationBar template.

Looking for some advice
Thank you

You can’t directly propagate data up through the extends chain.

I’m aware of at least three different ways to work around this limitation.

  • Add {% block <xxx> %}{% endblock %} directives in your class attributes allowing your downstream templates to set the right block with the right attribute.

  • Change your template structure such that your base template doesn’t extend navigationBar. Instead, have your base template allocation a block for the nagivation bar, but have your template include the navigation bar with the right information supplied to it - to be rendered within that block.

  • Add a custom context_processor to make some data element available within the extended template.

I’ve actually solved this using a templatetag. Possibly it’s overcomplicated, but it works :slight_smile:

I defined one called match

@register.filter
def match(value, path):
    """Usage: {% if value|match:"path" %}"""
    regex = re.compile(f"^{path}")
    return re.match(regex, value)

Then I load that to the navbar template and use it for each item to decide whether to add some extra formatting. In my case I’m making the text all uppercase, but you could do something different.

      <li class="nav-item px-2">
        <a
          class="nav-link {% if location.path|match:location.mission %} text-uppercase{% endif %}"
          href="{% url '<url link>' %}"
          >{% translate "Link text" %}</a
        >
      </li>