0

I am new to Django and am trying to figure out how to use dynamic CSS that is only active for the current category a user is on.

I have a side nav with some categories and whichever category the user is on should be active with the use of a class.

This is currently how I have things:

{% for category in categories %}
   <li><a href="{% url 'category' category.id %}"
         {% if category.id in request.path %}
             class="uk-text-bold"
         {% endif %} >{{ category.name }}</a></li>
         {% endif %}

This is obviously not correct and doesn't work so I imagine there is a proper way to do something like this and I'm just having a hard time understanding or finding that out.

Any help is appreciated! Thanks.

1
  • i believe you can find your answer here Commented Apr 27, 2020 at 13:32

2 Answers 2

2

you can make a html file e.g. style.html like this

{% load static %}
<style>

{% if your_condition %}

.active{
  /*your styles here*/
 }

{% endif %}
</style>

and include it in your main html file.

{% for category in categories %}
                                <li><a href="{% url 'category' category.id %}"
                                            class="classname">{{ category.name }}</a> 
                                </li>
                        {% endfor %}

you might need js to handle adding and removing active class to your element. it would be something like this

var categories = document.getElementsByClassName('classname');

for (var i = 0; i < tabs.length; i++) {
   tabs[i].addEventListener("click", function () {
    Array.prototype.forEach.call(document.getElementsByClassName("classname"), 
    function (tab) {
       tab.classList.remove('active');
    });
    this.classList.add('active');
   });
   }

I hope this will help you. also I suggest you to read django custom template tag .with template tags you can write a dynamic style tag for your html and call it when you need.

Sign up to request clarification or add additional context in comments.

1 Comment

Awesome, this is helpful! Thanks @Amir. I will look into this.
0

The second {% endif %} should be changed for an {% endfor %}. Then everything works the way you expect. I do this in my code all the time and I've had no problems with it.

{% for category in categories %}
  <li>
    <a href="{% url 'category' category.id %}"
      {% if category.id in request.path %} class="uk-text-bold" {% endif %} >
      {{ category.name }}
    </a>
  </li>
{% endfor %}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.