프로그래밍/Python

Django Template

Terry Cho 2013. 11. 21. 02:07


Django의 MVC 구조


원본- littlegreenriver.com

Template 란?


Template은 쉽게 이야기 하면 jsp 파일과 같다고 보면된다.

template은 string으로 파일에서 로딩할 수 도 있고 몇개의 notation을 통해서 구성된다.

마치 JSP의 <% %> 처럼

time.html 파일이 다음과 같을때 

current time is {{ current_time }}


이는 

current time is <%=current_time%> (JSP에서)와 같은 의미라고 보면된다.

실제 view 모듈에서 이 템플릿을 렌더링 하는데, 이때, tempalte에 있는 인자들을 대입한다.

    template = loader.get_template('time.html')

    current_time = datetime.datetime.now()

    context = Context({'current_time' : current_time })

    return HttpResponse(template.render(context))


Context 객체는 인자를 넘기는 일종의 컨테이너라고 보면되고,

Template에 정해진 변수 이름에, 실제 값을 맵핑 시킨후에,

Template을 이 Context로 렌더링 한다.



Template 위치에 대해서.


https://docs.djangoproject.com/en/1.4/ref/templates/api/#loader-types

django.template.loaders.app_directories.Loader

Loads templates from Django apps on the filesystem. For each app in INSTALLED_APPS, the loader looks for a templates subdirectory. If the directory exists, Django looks for templates in there.


This means you can store templates with your individual apps. This also makes it easy to distribute Django apps with default templates.


템플릿을 로딩하는 방법은 여러가지 Loader 설정에 따라 변경할 수 가 있는데,

그중에서 filesystemLoader와 app_directories.loader가 디폴트 설정되어 있다.

이때, app_directories.loaderㅢ 경우에는 app directory 아래의 /templates/ 디렉토리에서 template을 찾는다.


#views.py - mysite/reader/views.py

from django.http import HttpResponse

from django.template  import Context, loader

import datetime



def what_time_is_it(request):

    template = loader.get_template('time.html')

    current_time = datetime.datetime.now()

    context = Context({'current_time' : current_time })

    return HttpResponse(template.render(context))


이파일은 mysite라는 프로젝트의 reader라는 애플리케이션이다.

위의 파일 경로가 mysite/reader/views.py 이다

template의 파일명만 지정했는데, 이 경우

mysite/reader/templates/time.html을 찾게 된다.


Template 사용시 Dictionary 접근 방법

JSON을 변환하여 dictionary를 접근하면, 일반 python code에서

item['name']['firstname'] 이었다면

Template에서는 item.name.firstname 으로 해야 한다.


참고 : https://docs.djangoproject.com/en/1.4/ref/templates/api/#loader-types



그리드형