2011-11-24 1 views
6

우리는 많은 속성이 하이픈을 포함하는 명명 된 사용자 지정 데이터베이스에 구축 된 시스템, 즉이 이것에 대한 예외. 나는 이것을 극복하기 위해 밑줄을 사용하기 위해 모든 키 (및 서브 테이블 키)를 변환하지 않아야한다. 더 쉬운 방법이 있습니까?장고 템플릿에서 하이픈을 포함하는 사전 키에 어떻게 액세스합니까? 다음과 같이</p> <pre><code>user-name phone-number </code></pre> <p>이러한 속성은 템플릿에 액세스 할 수 없습니다 :</p> <pre><code>{{ user-name }} </code></pre> <p>장고가 발생

답변

8

개체를 재구성하지 않으려면 사용자 지정 서식 파일 태그가 여기에있는 유일한 방법 일 수 있습니다. 임의의 문자열 키로 사전에 액세스하려면 this question의 대답이 좋은 예입니다. 게으른 들어

: 당신과 같이 사용

from django import template 
register = template.Library() 

@register.simple_tag 
def dictKeyLookup(the_dict, key): 
    # Try to fetch from the dict, and if it's not found return an empty string. 
    return the_dict.get(key, '') 

:

: 당신은 임의의 문자열 이름으로 객체의 속성에 액세스하려면

{% dictKeyLookup your_dict_passed_into_context "phone-number" %} 

, 다음을 사용할 수 있습니다

from django import template 
register = template.Library() 

@register.simple_tag 
def attributeLookup(the_object, attribute_name): 
    # Try to fetch from the object, and if it's not found return None. 
    return getattr(the_object, attribute_name, None) 

다음과 같이 사용하십시오.

,
{% attributeLookup your_object_passed_into_context "phone-number" %} 

당신은 ('__'같은) 하위 속성에 대한 문자열 구분자의 일종으로 올 수 있지만, 나는 OrderedDict 사전 유형은 대시 지원

+1

이 솔루션을 사용했지만 변경되었습니다. 태그에서 필터로. 감사합니다. – jthompson

+0

이것은 확실히 작동하지만, dict을 값으로 포함하는 dict 내부에있는 키에 어떻게 액세스합니까? – Kim

3

불행히도 운이 좋지 않을 수도 있습니다. docs에서 :

변수 이름은 문자 (A-Z), 임의의 숫자 (0-9), 밑줄 또는 점으로 구성해야합니다.

+0

오른쪽. 또한 비슷한 질문을 발견했습니다. http://stackoverflow.com/questions/2213308/why-cant-i-do-a-hyphen-in-django-template-view – jthompson

1

:-) 숙제 떠날 것이다 : https://docs.python.org/2/library/collections.html#ordereddict-objects

이것은 OrderedDict 구현의 부작용 인 것 같습니다. 아래의 키 값 쌍은 실제로 집합으로 전달됩니다. 나는 OrderedDict의 구현이이 문제를 해결하기 위해 실제 dict 키로 전달 된 "키"를 사용하지 않을 것이라고 생각합니다.

이것은 OrderedDict 구현의 부작용이므로 의존하고 싶은 것이 아닐 수 있습니다. 그러나 그것은 효과적이다.

from collections import OrderedDict 

my_dict = OrderedDict([ 
    ('has-dash', 'has dash value'), 
    ('no dash', 'no dash value') 
]) 

print('has-dash: ' + my_dict['has-dash']) 
print('no dash: ' + my_dict['no dash']) 

결과 :

has-dash: has dash value 
no dash: no dash value