Вопрос

I passed 2 context variables {{ year_list }} and {{ current_year }} into a django template. I am looping through the {{ year_list }} and checking if {{ current_year }} is in the {{ year_list }}.

{% each_year in year_list %}
  {% if each_year == current_year %}
   <li class="active"><a href="{{ each_year }}">{{ each_year }}</a></li>
  {% else %}
   <li><a href="{{ each_year }}">{{ each_year }}</a></li>
  {% endif %}

It doesn't seem to be working. None of the list item has class='active'. But it prints the correct value when I put {{ each_year }} and {{ current_year }} right after {% each_year in year_list %}

I am actually using Class Based View YearArchiveView and I want to have a list of years and high-light the current year.

class SomeYearArchiveView(YearArchiveView):
    queryset = Some.objects.all()
    date_field = 'some_date'
    make_object_list = True

    def get_context_data(self, **kwargs):
        context = super(SomeYearArchiveView, self).get_context_data(**kwargs)
        context['year_list'] = [2010, 2011, 2012]
        context['current_year'] = self.request.path.split("/")[2]
        return context

What did I do wrong? Is there a better way to do this?

Это было полезно?

Решение

In function get_context_data -

context['year_list'] = [2010, 2011, 2012]
context['current_year'] = self.request.path.split("/")[2]

The year_list values are integer whereas current_year value is string. That's why they are not matching in template. Do this in your code -

context['current_year'] = int(self.request.path.split("/")[2])

This should work

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top