【Django】templateでdicrionaryの値を使う方法メモ

はじめに

今回やりたかったことは

views.py

list = [
  {"id":1, "name": "山田", "job_id": 1},
  {"id":2, "name": "田中", "job_id": 2},
  ・・・
]

job = {
  1: "サラリーマン",
  2: "農家",
  ・・・
}

return render(request, "index.html", { "list": list, "job": job })

上記の形でviewでセットされている値を使って
1 山田 サラリーマン
2 田中 農家
みたいな感じで表示したいということでした。

やり方が間違っているだけかもしれませんが以外とハマったのでメモ

できそうでできなかった方法

できなかった1(NG)

{% for row in list %}
  {{ job[row.job_id] }}
{% endfor %}

できなかった2(NG)

{% for row in list %}
  {% with job_id as row.job_id %}
  {{ job[job_id] }}
  {% endwith %}
{% endfor %}

解決策

やり方がわからなかったのでカスタムフィルタというのを使って解決しました

手順は
1. アプリケーションフォルダ内にtemplatetagsというフォルダを作成
2. templatetags/__init__.pyという空ファイルを作成
3. templatetags/custom_filters.pyを作成(名前は別でもよい)

custom_filters.py

from django import template
register = template.Library()

@register.filter
def get_dictionary(value, dict):
    return dict[value]

4. テンプレートで使う
index.html

{% for row in list %}
  {{ row.job_id|get_dictionary:job }}
{% endfor %}

カスタムフィルタはphpsmartyのものと似てる
けどこれだけのことをやるために本当にこんな手間かかるものなのだろうか。。。

もうちょっと調べてみないとわかりませんが、以上です