2017-12-14 3 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]를 표시하려면 django 템플릿에서 {% if d.keys in x %}을 호출합니까?

+1

여기 장고 템플릿 [tag] (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] 
} 

그런 다음 템플릿에서이 작업을 수행 할 수 있습니다

내 머리 부분에서이 모든 작업을 수행하므로 서식 또는 구문 버그가있을 수 있습니다. e 문서를 이전에 링크하면 필요한 위치로 연결됩니다.

+0

이것은 처음으로 템플릿 태그를 사용하는 것입니다. 귀하의 즉각적인 반응에 감사드립니다. 그것은 나를 위해 작동합니다. –

+0

@CarlosFabiera 기쁘다. 나는 그것을 내 자신의 테스트 프로젝트에 꽂았으며, 그것이 멋지게 플레이 할 수 있도록 약간의 변경을해야한다는 것을 깨달았다. 나는 당신이 같은 xD를해야만한다고 생각한다. – MCBama