Home > Blockchain >  Is there a way in Django to mask link in navbar according to the loaded template?
Is there a way in Django to mask link in navbar according to the loaded template?

Time:09-27

I would like to do a simple thing in Django but cannot find the "Django" way to do it and I am sure that there is one.

Let's imagine I have a simple navbar as follow:

<ul>
    <li>
        <a href="{% url 'home-index' %}">Home</a>
    </li>
    <li>
        <a href="{% url 'blog-index' %}">Blog</a>
    </li>
</ul>

When I am at the 'blog-index' url, I want to hide this specific link in the navbar.

Thanks for your help

CodePudding user response:

You can check the request.path in the template.

{% if request.path == "your_url" %}
    (dont show button)
{% endif %}

You can use the if statement to set the style to hidden for example.

If you want to use dynamic URL's, you could use a template tag:

# Put your navbar items in another HTML template.
@register.inclusion_tag('navbar.html', takes_context=True)
def navbar_tag(context):
    request = context['request']
    url_one = reverse('blog:your-index')
    url_two = reverse('blog:blog') # You get the gist, this could possibly be done automatically.
    return {
        "urls":{
            "url_one":url_one,
            "url_two":url_two,
        }
    }

And then in your template tag HTML template, you could use:

{% if request.path != urls.url_one %}

And in your normal template, you load the tag first, and can then just put it in place of your navbar items, like so:

{% load your_tag_library %}

{% navbar_tag %}

enter image description here

  • Related