Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dictionary lookup in django templates

{% for dispN0, tableDataSet0 in tabulatedTable.items %}
    {% for dispN in orderChanels %}     
        {% for antenaName, antenaLevel in tableDataSet0.{{dispN}}.items %}  
             <td>{{antenaName}}</td>    
        {% endfor %}
    {% endfor %}
{% endfor %}

Here {{dispN}} is integers numbers will come..like 36, 42, etc. If i give tableDataSet0.36.items it's working fine. But I need multiples in the place 36.

like image 901
Ganga U Avatar asked Oct 17 '22 11:10

Ganga U


1 Answers

You need to write an own template filter to lookup the value of a dictionary or an object:

Create a file like utils.py within a templatetags folder within your app like this:

app_dir/
├── __init__.py
├── models.py
  ...
├── templatetags/
│   ├── __init__.py  # required for python 2.7
│   └── utils.py
  ...
└── views.py

And fill it with this content:

from django import template

register = template.Library()

@register.filter
def lookup(value, key):
    return value.get(key, [])

Now you can use this filter in your template like this:

{% load utils %}

{% for dispN0, tableDataSet0 in tabulatedTable.items %}
    {% for dispN in orderChanels %}

        {% with tableData = tableDataSet0|lookup:dispN %}
            {% for antenaName, antenaLevel in tableData.items %}
                <td>{{antenaName}}</td> 
            {% endfor %}
        {% endwith %}

    {% endfor %}
{% endfor %}

Read more about

  • Custom template tags and filters
  • the {% with %} templatetag
like image 119
fechnert Avatar answered Oct 27 '22 08:10

fechnert