티스토리 뷰
Django Template Loader
다수 디렉토리 목록에서 지정 상대경로를 가지는 템플릿을 찾음
• app_directories.Loader 와 filesystem.Loader
위 Loader를 통해, 템플릿 디렉토리가 있을 후보 디렉토리 리스트를 작성, 이는 장고 서버 초기 시작시에만 1회 작성
주로 아래 함수를 통해 Template 파일들을 활용합니다.
• render : 템플릿을 렌더링은 문자열로 HttpResponse 객체를 리턴
• render_to_string : 템플릿 렌더링한 문자열을 리턴
response = render(request, 'blog/post_list.html', context_params) # 변수 목록을 사전 타입으로 받는다. ## Return 타입 HttpResponse
welcome_message = render_to_string('accounts/signup_welcome.txt', context_params) # 변수 목록을 사전 타입으로 받는다. ## Return 타입 STR
app_directories.Loader
settings.INSTALLED_APPS에 설정된 앱 디렉토리 내 templates 경로 에서 템플릿 파일을 찾는다. (# settings.py 'APP_DIRS'True)
# OPTIONS= ['loaders' : ]로 정의도 가능 하다.
accounts/templates/ shop/templates/ blog/templates/ dojo/templates/ askdjango/templates # 프로젝트 레벨에 쓸 템플릿 파일만 저장 (filesystem.Loader에서 찾을수 있도록 설정) |
filesystem.Loader 프로젝트 전반적으로 쓰일 템플릿 파일은 "특정앱/templates/" 경로가 아닌 별도의 경로에 저장이 필요 # 프로젝트/settings.py 에 후보지 디렉토리 경로 지정 TEMPLATES = [{ 'DIRS': [ os.path.join(BASE_DIR, '프로젝트명', 'templates'), ], }] |
앱 디렉토리 별로 각 앱을 위한 템플릿 파일을 위치
- blog앱용 템플릿은 blog/templates/ 경로에 두는 것이 관리성 좋음
- shop앱용 템플릿은 shop/templates/ 경로에 두는 것이 관리서 좋음
(중요) 앱 디렉토리 로더 활성화된 앱 및 템플릿 디렉토리를 후보군에 저장 한다.
후보군이 작성되고 후본군에서 "post_List.html"파일을 찾는다, 모든 후보군에 파일이 없다면 오류 발생
render(request, 'blog/post_list.html') 이 호출되면 blog/templates/blog/post_list.html 파일 체크, 없으면 다음 shop/templates/blog/post_list.html 파일 체크, 없으면 다음 diary/templates/blog/post_list.html 파일 체크, 없으면 다음 프로젝트명/templates/blog/post_list.html 파일 체크, 없으면 다음 마지막까지 검사해서 없을 경우, TemplateDoesNotExist 예외 발생 |
ex) render (request, "post_list.html") 요청 시 전 프로젝트에 대한 탐색이 시작되고 우선순위가 높은 프로젝트의 탬플릿으로 실행이됨 (중복이 발생해도 우선순위가 높은걸로 실행)
해당 이유로 인해, 앱 명/templates/으로 생성하여 유일성을 보장한다.
blog/templats/post_list.html - shop/templats/post_list.html 각 앱 내 뷰에서 render(request, 'post_list.html') 와 같이 쓴다면, blog/shop 앱 모두에서 항상 blog/templates/post_list.html 템플릿만 사용 - blog/templats/post_list.html : post_list.html 경로로 찾는다. - shop/templats/post_list.html : post_list.html 경로로 찾는다. |
템플릿 경로가 겹치지 않게 하는 방법
• 방법1) 항상 템플릿 파일을 생성할 때마다, 개발자가 템플릿 파일명이 중복되지 않는지 체크해서 생성한다.
• 방법2) namespace 역할로서 앱 이름의 디렉토리를 중간에 둔다.
• 장고는 다른 앱이 같은 이름을 가지는 것을 허용하지 않는다.
예시
- blog/templats/blog/post_list.html : blog/post_list.html 경로로 찾는다.
- shop/templats/shop/post_list.html : shop/post_list.html 경로로 찾는다.
render_to_string 샘플 ## 회원가입 시 가입환영 메일
accounts/signup_welcome.txt
안녕하세요. {{ name }}님. {{ name }}님께서는 {{ when }}에 가입하셨습니다.
감사드립니다.
from django.template.loader import render_to_string welcome_message = render_to_string('accounts/signup_welcome.txt', { 'name': '포꾼', 'when': '2017년 12월 9일 오후 3시', }) print(welcome_message) |
"""본 내용은 AskDjango VOD, "장고 차근차근 시작하기" 강의내용을 참고하여 작성했습니다.(https://nomade.kr/)"""
'Python > * Django' 카테고리의 다른 글
13. Django 템플릿 엔진 - 템플릿 태그 (0) | 2017.12.15 |
---|---|
12. URL Reverse (0) | 2017.12.13 |
10. Django 템플릿 상속 (0) | 2017.12.13 |
9. Model Relationship Fields (2) | 2017.12.13 |
8. Http Status Code 404 (0) | 2017.12.13 |