Djangoのテンプレートで、キーに変数を指定して辞書にアクセス

context_dataに辞書が渡されていて、テンプレートでアクセスする例

views.py

from django.views.generic import TemplateView

class HomeView(TemplateView):
    template_name = 'sample/home.html'

    def get_context_data(self, **kwargs):
        ctx = super(HomeView, self).get_context_data(**kwargs)
        ctx.update(dict(dictionary={1: 'one', 2: 'two', 3: 'three'}))
        return ctx

home = HomeView.as_view()


キーがわかっていれば以下のようにテンプレートから辞書にアクセスできる。

home.html

{{ dictionary.1 }}
{{ dictionary.2 }}
{{ dictionary.3 }}


キーが変数だとこの方法ではアクセス出来ない

{% with 1 as id %}
    {{ dictionary.????}}
{% endwith %}


この場合テンプレートタグを作成して対応できる

lookup.py

# coding=utf-8
from django import template
register = template.Library()


@register.filter(name='lookup')
def lookup(value, arg, default=""):
    if arg in value:
        return value[arg]
    else:
        return default
{% load lookup %}

{% with 1 as id %}
    {{ dictionary|lookup:id }}
{% endwith %}

{% with 4 as id %}
    {{ dictionary|lookup:id|default:".."}}
{% endwith %}