2017-12-14 12 views
0

私は、次の辞書を持っている:表示辞書ファイル

d = {'21': 'test1', '11': 'test2'} 

{% with '18 17 16 15 14 13 12 11 21 22 23 24 25 26 27 28' as list_upper %} 
{% for x in list_upper.split %} 

    {% if x in dental_position %} 
    <input type="text" placeholder = "{{ x }}" class="form-control" name="tooth[]" value="{{display dict.value here}}"> 
    {% else %}<input type="text" placeholder = "{{ x }}" class="form-control" name="tooth[]"> 
    {% endif%} 


{% endfor %} 

d[key]からの値が

どのようlist_upperに発見されたとき、私は、入力されたテキスト値の属性の内部d[value]を表示したいです私は{% if d.keys in x %}をdjangoテンプレートと呼んでいますか?

+1

ここではdjangoテンプレート[タグ](https://docs.djangoproject.com/en/2.0/howto/custom-template-tags/)が必要です。この問題はかなり簡単になります。 – MCBama

+0

あなたのコンテキストで 'list_upper'を定義しなかった理由はありますか?あなたはあなたのforループのためにやっているあなたのテンプレートで狂ったコーディングする必要はありません。 – MCBama

答えて

1

このようなタグファイルを作成します。

# tags.py 
def is_dict_key(key, d): 
    return key in d 

def get_dict_value(d, key): 
    try: 
     return d[key] 
    except KeyError as e: 
     print(e) 
     return None 

ビューと仮定すると、コンテキストに渡し、次のようになります

{% load tags %} 
{% for x in list_upper %} 

    {% if x|is_dict_key:dental_position %} 
     <input type="text" placeholder = "{{ x }}" class="form-control" name="tooth[]" value="{{dental_position|get_dict_value:x}}"> 
    {% else %} 
     <input type="text" placeholder = "{{ x }}" class="form-control" name="tooth[]"> 
    {% endif%} 


{% endfor %} 

context = { 
    'dental_position': {21: 'test1', 11: 'test2'} 
    'list_upper': [18, 17, 16, 15, 14, 13, 12, 11, 21, 22, 23, 24, 25, 26, 27, 28] 
} 

は、その後、あなたのテンプレートで、あなたがこれを行うことができます

私は頭の中からこれをすべてやっているので、フォーマットや文法のバグがあるかもしれません。私が以前にリンクしたドキュメントは、必要な場所にあなたを導きます。

+0

これは初めてのテンプレートタグの使用です。すぐにお返事ありがとうございます。わたしにはできる。 –

+0

@CarlosFabieraそれはうまくいった。私はそれを自分のテストプロジェクトに組み込み、それがうまくいくようにいくつかの変更を加える必要があることを認識しました。私はあなたが同じxDをしなければならなかったと思います – MCBama

関連する問題