1

I have the following data in my views.

months = [1,2,3,4,5,6,7,8,9,10,11,12]
mydict = {3:'a',4:'b'}

The key means month,if this month exists value,then render the value,else leave blank. Here's my template.

{% for j in months %}
    {% if mydict.j %}
        <th class="align-middle">{{ mydict.j }}</th>
    {% else %}
        <th class="align-middle"></th>
    {% endif %}
{% endfor %}

But the result always is blank. I can access the value by mydict.3,but i can't get the value by mydict.j with a forloop.

Zorba
  • 33
  • 3
  • By using `{{ mydict.j }}`, you try to perform a lookup `mydict['j']`. You can not perform a dictionary lookup in Django templates (unless making custom template filters etc.). This is done *on purpose*. This logic should be done in the *view* not in the template. – Willem Van Onsem Mar 14 '20 at 11:46

1 Answers1

0

If you write {{ mydict.j }}, then Django aims to lookup the value mydict['j'], not mydict[j].

Dictionary lookups and function calls (with arguments) are deliberately not allowed in a template, such that developers are encouraged to write business logic in the view not in the template. You can write a custom template filter, or make use of the jinja template renderer to allow this.

But it might be more sensical to do the mapping in the view:

def some_view(request):
    mydict = {3:'a',4:'b'}
    monthsanddict = [(x, mydict.get(x)) for x in range(1, 13)]
    return render(request, 'some_template.html', {'monthsanddict': monthsanddict})

and in the template, you can then render this with:

{% for j, mydictj in monthsanddict %}
    {% if mydictj %}
        <th class="align-middle">{{ mydictj }}</th>
    {% else %}
        <th class="align-middle"></th>
    {% endif %}
{% endfor %}
Willem Van Onsem
  • 443,496
  • 30
  • 428
  • 555