본문 바로가기

웹/Django

[Django] Template과 렌더링 / 2021.08.25

* 참고 자료 : 코드잇 Django 강의


앞선 포스팅에서 문자열 Hello, Django! 를 출력하기 위해 코드를 다음과 같이 적어줬었다.

foods 안의 views.py


하지만 여기서 단순히 문자열만 있는게 아니라 여러 요소가 포함된 코드를 출력하려면 views파일이 너무 어지럽혀진다.
만약 더 많은 요소를 views파일을 더럽히지 않으면서 리턴 하고 싶다면 어떻게 해야 할까?

1. HTML 파일로 만들기
장고에서는 HTML과 같이 화면 구성을 담당하는 것을 Template라고 한다.
많은 요소들을 더 깔끔하게 관리하기 위해서 새로운 HTML 파일을 생성해보자.

(1) templates 디렉터리 생성
우리는 foods앱을 작업 중이니 foods앱 안에 Template파일을 넣어줄 templates디렉터리를 생성하자.

foods 안의 templates


그다음 templates 디렉터리 안에 앱 이름을 그대로 사용한 foods디렉터리를 생성하자.

foods안의 templates안의 foods


(2) html 파일 생성
생성한 templates 안의 foods디렉터리에 index.html을 생성하자.
이 index.html을 index template라고도 한다.

templates안의 foods안의 index.html


생성한 html안에 코드를 적어주자.

index.html

이런 식으로 적어주었다.
이제, 이 template을 유저에게 보여주자. 이 표현을 다르게 말하면 "Template을 Render 한다"라고 한다.


(3) Template을 Render 하기
template을 유저에게 보여주기 위해 foods안의 views파일을 다음과 같이 수정하자.

foods안의 views.py


여기서 render함수를 사용하는데, 파라미터로 request를 넘기고 두 번째 파라미터로 template의 경로를 넘긴다.
이 render함수는 우리가 넘겨준 request와 template을 토대로 하나의 HttpResponse객체를 리턴해준다.

(4) 웹페이지 확인하기
서버를 실행하고 주소 뒤에 경로를 적어주면,


index.html 내용이 출력되는 것을 확인할 수 있다!

* render 함수
render 함수에 대하여 더 자세이 알아보고 싶으면,

https://docs.djangoproject.com/en/2.2/topics/http/shortcuts/#django.shortcuts.render

 

Django shortcut functions | Django documentation | Django

Django The web framework for perfectionists with deadlines. Overview Download Documentation News Community Code Issues About ♥ Donate

docs.djangoproject.com


이 사이트를 확인하자.