자바스크립트를 허용해주세요.
[ 자바스크립트 활성화 방법 ]
from Mohon Aktifkan Javascript!
 

[Django] 4장. Django 템플릿 작성 - HTML 템플릿 작성 및 렌더링

728x90

✅ 1.템플릿 폴더 구조 설정

Django는 기본적으로 templates/ 폴더에서 테블릿을 찾아 화면에 반환합니다.

프로젝트/
│
├─ myapp/
│  ├─ templates/
│  │  └─ myapp/
│  │     └─ example.html
│  └─ views.py
│
├─ manage.py
└─ settings.py

 

// settings.py
TEMPLATES = [
    {
        ...
        'DIRS': [BASE_DIR / 'templates'],  # 프로젝트 전역 템플릿 폴더
        ...
    },
]

✅ 2. HTML 템플릿 기본 문법

  • example.html
<!DOCTYPE html>
<html lang="ko">
  <head>
    <meta charset="UTF-8" />
    <title>{{ title }}</title>
  </head>
  <body>
    <h1>{{ title }}</h1>

    <ul>
      {% for item in items %}
      <li>{{ item }}</li>
      {% empty %}
      <li>목록이 비어 있습니다</li>
      {% endfor %}
    </ul>
  </body>
</html>

✅ 3. 뷰(View)에서 템플릿 렌더링

  • views.py
from django.shortcuts import render

def example_vie(request):
    # 예시 뷰 함수 
    context = {
        "title": "Template Example",
        'heading': "Django Template Testing",
        "description": "This is a simple example of a Django template.",
        "items": ["Keyboard", "Mouse", "Monitor", "CPU"],
    }
    return render (request, "myapp/example.html", context)

✅ 4. URL 연결 

  • myapp/urls.py (생성)
from django.urls import path
from . import views

urlpatterns = [
       path('example/', views.example_view, name= "example"),
]
  • config/urls.py
from django.urls import path
from django.contrib import admin
from django.urls import include
# from django.views.generic import RedirectView
# from myapp.views import product_list

urlpatterns = [
    path('admin/', admin.site.urls),
    path ('', include('myapp.urls'))
    # path('', RedirectView.as_view(url='/products/')),
    # path('products/', product_list, name='product_list'),
]

5. 서버 실행

python manage.py runserver

 

브라우저에서 http://127.0.0.1:8000/example/ 로 접속해 적용되었는지 확인합니다.


 

 

GitHub - Koras02/djago-bloging: https://thinky.tistory.com/category/Back-End/Django

https://thinky.tistory.com/category/Back-End/Django - Koras02/djago-bloging

github.com

 

728x90
LIST