[python] 장고 템플릿 변수로 사전 값을 찾는 방법

mydict = {"key1":"value1", "key2":"value2"}

Django 템플릿에서 사전 값을 조회하는 일반적인 방법은 {{ mydict.key1 }}, {{ mydict.key2 }}입니다. 키가 루프 변수이면 어떻게 되나요? 즉 :

{% for item in list %} # where item has an attribute NAME
  {{ mydict.item.NAME }} # I want to look up mydict[item.NAME]
{% endfor %}

mydict.item.NAME실패합니다. 이 문제를 해결하는 방법?



답변

사용자 정의 템플릿 필터를 작성하십시오.

from django.template.defaulttags import register
...
@register.filter
def get_item(dictionary, key):
    return dictionary.get(key)

(I 사용 .get하므로 키가 존재하지 않는 경우, 그것은 아무것도 반환하지 않습니다 것을. 당신이 경우에 dictionary[key]그것은을 올릴 것이다 KeyError다음.)

용법:

{{ mydict|get_item:item.NAME }}


답변

루프의 사전에서 키와 값을 모두 가져옵니다.

{% for key, value in mydict.items %}
    {{ value }}
{% endfor %}

나는 이것을 쉽게 읽을 수 있으며 특별한 코딩이 필요하지 않습니다. 어쨌든 일반적으로 루프 내부의 키와 값이 필요합니다.


답변

기본적으로 할 수 없습니다. 점은 속성 조회 / 키 조회 / 슬라이스에 대한 구분자 / 트리거입니다.

점은 템플릿 렌더링에 특별한 의미가 있습니다. 변수 이름의 점은 조회를 나타냅니다. 특히 템플릿 시스템이 변수 이름에서 점을 발견하면 다음 순서로 다음 조회를 시도합니다.

  • 사전 검색. 예 : foo [ “bar”]
  • 속성 조회. 예 : foo.bar
  • 리스트 인덱스 조회. 예 : foo [bar]

그러나 인수를 전달할 수있는 필터를 만들 수 있습니다.

https://docs.djangoproject.com/en/dev/howto/custom-template-tags/#writing-custom-template-filters

@register.filter(name='lookup')
def lookup(value, arg):
    return value[arg]

{{ mydict|lookup:item.name }}


답변

template_filters.py아래 내용으로 내 앱에 python 파일을 만들면 작업이 완료되었습니다.

# coding=utf-8
from django.template.base import Library

register = Library()


@register.filter
def get_item(dictionary, key):
    return dictionary.get(key)

사용법은 culebrón이 말한 것과 같습니다.

{{ mydict|get_item:item.NAME }}


답변

나는 비슷한 상황을 겪었다. 그러나 다른 솔루션을 사용했습니다.

내 모델에서는 사전 조회를 수행하는 속성을 만듭니다. 그런 다음 템플릿에서 속성을 사용합니다.

내 모델에서 :-

@property
def state_(self):
    """ Return the text of the state rather than an integer """
    return self.STATE[self.state]

내 템플릿에서 :-

The state is: {{ item.state_ }}


답변

내가 말할 수 없기 때문에 대답의 형태로 이것을 할 수 있습니다 : culebrón ‘s answer 또는 Yuji ‘ Tomita’Tomita ‘s answer
기반으로 함수에 전달 된 사전은 문자열 형태이므로 ast를 사용하십시오 . literal_eval 에서와 같이, 먼저 사전에 문자열을 변환하는 .

이 편집을 통해 코드는 다음과 같아야합니다.

@register.filter(name='lookup')
def lookup(value, arg):
    dictionary = ast.literal_eval(value)
    return value.get(arg)

{{ mydict|lookup:item.name }}


답변

환경 : 장고 2.2

  1. 예제 코드 :


    from django.template.defaulttags import register

    @register.filter(name='lookup')
    def lookup(value, arg):
        return value.get(arg)

이 코드를 templatemgr이라는 프로젝트 폴더의 template_filters.py 파일에 넣습니다.

  1. 필터 코드의 위치에 상관없이 해당 폴더에 __init__.py 가 있는지 확인하십시오

  2. projectfolder / settings.py 파일의 템플릿 섹션에있는 라이브러리 섹션에 해당 파일을 추가하십시오. 나를 위해, 그것은 Portfoliomgr / settings.py입니다



    TEMPLATES = [
        {
            'BACKEND': 'django.template.backends.django.DjangoTemplates',
            'DIRS': [os.path.join(BASE_DIR, 'templates')],
            'APP_DIRS': True,
            'OPTIONS': {
                'context_processors': [
                    'django.template.context_processors.debug',
                    'django.template.context_processors.request',
                    'django.contrib.auth.context_processors.auth',
                    'django.contrib.messages.context_processors.messages',
                ],
                'libraries':{
                    'template_filters': 'portfoliomgr.template_filters',
                }
            },
        },
    ]
  1. html 코드에서 라이브러리를로드하십시오.

    
    {% load template_filters %}