티스토리 뷰

Context Variable Lookup

장고 템플릿은 점(.)을 이용해서 다양한 자료형을 템플릿에서 참조한다. context에서 전달되는 다양한 자료형의 값들을 살펴보고 템플릿에서는 어떻게 쓰이는지 보도록 하자.

참고 원문 : http://www.djangobook.com/en/2.0/chapter04.html

1. Dictionary(사전)


사전 정의 : person = {'name' : 'Sally', 'age' : '43'}
문맥(Context) 변수 입력 : {'person' : person}
원형(Template) 참조 : {{ person.name }}

>>> from django.template import Template, Context
>>> person = {'name': 'Sally', 'age': '43'}
>>> t = Template('{{ person.name }} is {{ person.age }} years old.')
>>> c = Context({'person': person})
>>> t.render(c)
u'Sally is 43 years old.'

2. Attribute (객체의 속성)


객체(Object) 정의 : dateClass 이 오브젝트는 year, month, day 속성(클래스 멤버)을 갖고 있다고 가정하자.
문맥(Context) 변수 입력 : {'date' : dateClass }
원형(Template) 참조 : {{ date.month }}

>>> from django.template import Template, Context
>>> import datetime
>>> d = datetime.date(1993, 5, 2)
>>> d.year
1993
>>> d.month
5
>>> d.day
2
>>> t = Template('The month is {{ date.month }} and the year is {{ date.year }}.')
>>> c = Context({'date': d})
>>> t.render(c)
u'The month is 5 and the year is 1993.'

3. Method call (클래스 메쏘드 호출)


메쏘드 정의 : Person 클래스는 getAge() 메쏘드를
문맥(Context) 변수 입력 : {'coloritems' : a}
원형(Template) 참조 : {{ coloritems.2 }} 리스트의 'blue'가 선택된다.

>>> from django.template import Template, Context
>>> class Person(object):
...     def __init__(self, first_name, last_name):
...         self.first_name, self.last_name = first_name, last_name
>>> t = Template('Hello, {{ person.first_name }} {{ person.last_name }}.')
>>> c = Context({'person': Person('John', 'Smith')})
>>> t.render(c)
u'Hello, John Smith.'

4. List-index lookup (e.g., foo[2])


리스트 정의 : a = ['red', 'green', 'blue', yellow']
문맥(Context) 변수 입력 : {'coloritems' : a}
원형(Template) 참조 : {{ coloritems.2 }} 리스트의 'blue'가 선택된다.

>>> from django.template import Template, Context
>>> t = Template('Item 2 is {{ items.2 }}.')
>>> c = Context({'items': ['apples', 'bananas', 'carrots']})
>>> t.render(c)
u'Item 2 is carrots.'