0

I am currently working on a personal blog in Django to get better at web programming, but I have encountered a slight problem. My idea was to make the webpage able to know which menu element is the active one, passing an argument from the views.py and to the template. Thus, I am here to ask why that might be so.

This is my template:

{% block menu %}

        <style> li a:nth-child({{ active }}) { text-decoration: underline; } </style>

    <li><div id="title"><span>{</span> <a href="#">Title</a> <span>}</span></div></li>
    <li><a href="/">Home</a></li>
    <li><a href="#">About</a></li>
    <li><a href="#">Contact</a></li>
    <li><a href="#">Work</a></li>

{% endblock menu %}

And here is my views.py (for the specific page):

def detail(request, blog_id):
    blog = get_object_or_404(BlogPost, pk=blog_id)
    return render(request, 'blogs/post.html', {'blog': blog, 'active': 1})

I have tried targetting the nth-child of the li's, but that didn't work either. I have also tried putting in fixed numbers as a parameter for the nth-child. Alas, to no avail.

Can anyone help me? Are there any better ways to do this?

gloriousCatnip
  • 411
  • 1
  • 6
  • 18

1 Answers1

1

There are a couple of issues here: nth-child looks for the n-th child element in a group. Your code as it is currently would style the nth a element inside a li tag - but there's only ever one a in each li. You need to target the li:

li:nth-child({{ active }}) a { text-decoration: underline; }

You also need to make sure that the li items have nothing else alongside them (including style tags), as this will mess up the counter. The template code you've posted above is incomplete (we can't see the outer ul/ol) but if there are other elements inside it then that is a problem.

That said, I don't think that this is the best approach - dynamic inline styling is not a robust, maintainable solution. A much more common pattern is to add an active class to the active list item, and then have styling for this in your core (static) CSS. See this question for some ideas on how to implement that.

Community
  • 1
  • 1
solarissmoke
  • 30,039
  • 14
  • 71
  • 73