[Django] DAY14. 서비스에 맞는 Templates 프로젝트 구성하기: block, include, extends

이하얀·2024년 2월 14일
0

2024년 2월 14일 수요일

📙 강의 내용 요약

  • 새 폴더 “templates” 생성
  • anonymous/settings.py의 TEMPLATES 내 DIRS에 templates 추가
    • 폴더 가장 바깥쪽에 있는 templates도 사용할 것이라는 명령을 주는 것.
TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [
            'templates',
        ],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]
  • templates/index.html 생성
    <html>
        <head>
            <title>Anonymous</title>
        </head>
        <body>
            익명 게시판 서비스
        </body>
    </html>
  • anonymous/urls.py
    from django.urls import path
    
    urlpatterns = [
        path("", aaaa) // aaaa=함수 자리, 아직 만들어야 함.
    ]
  • board/views.py
    from django.shortcuts import render
    
    # Create your views here.
    def board(request):
        if request.method == 'GET':
            return render(request, 'index.html')
    • 다시 urls.py에 와서 추가
      from django.urls import path
      from board.views import board
      
      urlpatterns = [
          path("", board, name="board")
      ]
  • 서버 실행
  • views.py에 context 추가 및 index.html에 변수 추가
    from django.shortcuts import render
    
    # Create your views here.
    def board(request):
        if request.method == "GET":
            context = {
                "title":"안녕 베어유?"
            }
            return render(request, 'index.html', context=context)
    ...
    <body>
            익명 게시판 서비스
            {{title}}
        </body>
    ...
  • templates 폴더에 “common”, “page” 새 폴더 추가
  • common/base.html에 index.html 내용 붙여넣기
  • index.html은 page 폴더로 이동
    //base.html
    <html>
    
        <head>
            <title>Anonymous</title>
        </head>
        
        <body>
            {% block content %}
            {%endblock %}
        </body>
    </html>
    
    //index.html
    {% extends 'common/base.html' %}
    
    {% block content %}
    내용 입력
    {% endblock %}
  • board/views.py 수정
    ...
            return render(request, 'page/index.html', context=context)

  • 테스트
    • index.html 수정
      {% extends 'common/base.html' %}
      
      {% block content %}
      {{ title }} 잘 나오니???
      {% endblock %}
  • templates 폴더 내 “component” 새 폴더 추가& nav.html 생성
    <div style="background-color: red;width: 100%;height:100px;">
        여기는 네비게이션 영역입니다!
    </div>
  • base.html에서 네비게이션 불러오기
    <html>
    
        <head>
            <title>Anonymous</title>
        </head>
        
        <body>
            {% include "component/nav.html" %}
    
            {% block content %}
            {%endblock %}
        </body>
    </html>

  • 숙제 : component 내부에 footer.html 만들기
    //footer.html
    <footer>
        <div class="container">
            <div class="row">
                <div class="col-md-6">
                    <p>&copy; 2024 Your Company. All rights reserved.</p>
                </div>
            </div>
        </div>
    </footer>
    
    //base.html
    <html>
    
        <head>
            <title>Anonymous</title>
        </head>
        
        <body>
            {% include "component/nav.html" %}
            {% block content %}
            {%endblock %}
            {% include "component/footer.html" %}
        </body>
    </html>

♻️ 느낀점&인사이트

오늘은 웹 프론트에 해당하는 내용을 학습하는 강의였다.

templates라는 폴더를 만들고, 이를 django가 바라볼 수 있도록 settings.py를 수정해주면 HTML을 렌더링해 사용할 수 있는 방식이었다.

그리고 각 html에서 block, include, extends라는 태그를 {% %}안에 넣어주어 선언해주면 각 폴더에 만들어둔 base.html, nav.html, index.html, footer.html…등을 모두 종합해준 프론트 화면을 구성할 수 있다.

폴더 구조는 크게 templates 안에 가장 자주 사용하는 html을 저장하는 ‘common’, 웹페이지의 네비게이션, 푸터 등을 저장하는 ‘component’, 웹 페이지의 내용에 해당하는 부분을 저장하는 ‘page’ 폴더가 있는 형태로 구성되어 있다.

common에는 주로 base.html이라는 페이지를 저장해 웹페이지의 구조를 작성한다.

component에는 nav.html, footer.html과 같은 요소를 저장한다.

그리고 page에는 index.html이라는 내용이 담긴 페이지를 저장한다.

이렇게 django를 활용해 웹 프론트에 해당하는 내용을 빠르게 렌더링하고, 바로 확인해보는 과정을 통해 익명 게시판의 프론트를 만들어보기 전 연습을 해볼 수 있었다.

다만, 아직 태그에 대한 이해가 조금 부족한 것 같아서 따로 공부를 더 해야겠다.

내일도 화이팅!!

profile
언젠가 내 코드로 세상에 기여할 수 있도록, BE 개발 기록 노트☘️

0개의 댓글