본문 바로가기
히치하이커 개발/Django

[Django] HTML template 뼈대 만들기 - include, extends, block

by 헬보이 2022. 10. 25.
반응형

Django 에서 HTML 뼈대를 만들때 extends 로 base.html 를 상속받고, header 와 footer 등은 include 로 가져와서 반영하게된다. 내용물인 content 는 block 로 정의해서 제공한다. 

말만들어서는 무슨뜻인지 알기 어려우니 아래처럼 정리해봤다. 

 

HTML 의 구조는 다음과 같습니다. 

  • base.html
    • head.html
    • header.html
      • {% contents %}
    • footer.html

 

base.html

<!DOCTYPE html>
<html lang="ko">
    {% include 'head.html' %}
    <body>
    {% include 'header.html' %}

       {% block content %}
       {% endblock %}

    {% include 'footer.html' %}
    </body>
</html>

TIP. header 나 footer 에 css 나 js 를 사용하기 위해서 {% static 'js/scripts.js' %} 이런식으로 static 를 쓰는 경우가 있는데 이럴떄는 반드시 static 가 사용되는 header 나 footer 파일의 최상단에 {% load static %} 을 해줘야 static 를 인식할수 있다. 

 

content

{% block content %}
{% endblock %}

이렇게 표현되는 content 는 base.html 에 컨텐츠의 시작과 끝을 지정해주고 외부의 컨텐츠가 정의된 html 에서 base.html 를 상속해서 사용하면된다. 

 

urls.py

urlpatterns = [   
    path('front', views.front),
]

유입되는 url 이 front 일때 아래처럼 content 가 정의되어 있는 html 만 가리키면 base.html 을 상속받았기에 모두 적용되어 보여진다.

 

views.py

def front(request):
    return render(request, 'front/category_content.html')

 

category_content.html

{% extends "base.html" %}
{% block content %}
<!-- Section-->
<section class="py-5">

#컨텐츠 html 내용 코딩

</section>
{% endblock%}

 

이처럼 html 을 별도로 지정할때 templates 폴더를 manage.py 와 같은 레벨에 생성해서 사용하면된다. 

그리고 templates 를 지정할때는 settings.py 의 설정중 TEMPLATES 부분을 아래와 같이 수정하면된다. 

템플릿 설정파일의 디렉토리 설정 예시 이미지
템플릿

위와 같이 정의하거나 

'DIRS': [os.path.join(BASE_DIR,'templates')]

이런식으로 정의 할수 있다.

댓글