Frage

I want to render in template data like that: [{'name': 'Some name', 'description': 'Description for this item'}]

I try to use this code:

{% for item in source_data %}
    <tr>
        <td>{{ item['name'] }}</td>
        <td>{{ item['description'] }}</td>
    </tr>
{% end %}

It doesn't work, because I receive KeyError: 'description' exception.

But if I change second placeholder to {{ item.get('description') }} it works as expected (Correct data from dictionary was printed, not default value).

What can produce this kind of error?

War es hilfreich?

Lösung

Looks like not all of your dictionaries have description key.

Instead of directly getting the value by key, use dictionary get() method, that won't throw KeyError if a key wasn't found:

{% for item in source_data %}
    <tr>
        <td>{{ item['name'] }}</td>
        <td>{{ item.get('description', 'No description') }}</td>
    </tr>
{% end %}

Demo:

>>> from tornado import template
>>> source_data = [
...     {'name': 'Some name', 'description': 'Description for this item'},
...     {'name': 'test'}
... ]

>>> template1 = template.Template("""
... {% for item in source_data %}
...     {{ item['description'] }}
... {% end %}
... """)

>>> template2 = template.Template("""
... {% for item in source_data %}
...     {{ item.get('description', 'No description found') }}
... {% end %}
... """)

>>> print template1.generate(source_data=source_data)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "tornado/template.py", line 278, in generate
    return execute()
  File "<string>.generated.py", line 7, in _tt_execute
KeyError: 'description'
>>> print template2.generate(source_data=source_data)

    Description for this item

    No description found

Hope that helps.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top