티스토리 뷰

웹/django

[Django, python] Django 템플릿 엔진

코딩계란 2024. 1. 25. 15:48
728x90

템플릿 엔진을 이용한 출력

  • 일반 HTML은 자바스크립트를 이용하지 않으면 동적인 데이터를 출력할 수 없다. HTML과 CSS는 정적 파일로 한 번 만들어지면 수정이 불가능하다. 
  • 템플릿 엔진은 서버의 데이터를 출력하는 파일에 전달을 해서 템플릿 엔진의 문법으로 출력하는 코드를 작성하면 이를 HTML코드로 번역을 해서 출력문을 만들어 준다. 
  • django에서는 확장자가 html이지만 정적 파일이 아니라서 templates 디렉토리에 작성한다. 
#실습에 사용한 HTML 파일 
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>
<body>
  <div align = "center" class="body">
    <h2>상품 목록 화면</h2>
    <table border="1">
      <tr class="header">
        <th align="center" width = "80"> 상품ID</th>
        <th align="center" width = "320"> 상품 이름</th>
        <th align="center" width = "100"> 가격</th>
      </tr>
      {% for item in data %}
        <tr class="record">
          <td align="center">{{item.itemid}}</td>
          <td align="center">{{item.itemname}}</td>
          <td align="center">{{item.price}}원</td>
        </tr>
      {% endfor %}
    </table>

  </div>
</body>
</html>

전체보기에 css(정적 파일을 적용)

전 게시물의 마지막 실습에 이어서 진행하였습니다. 이전 게시물을 참고해주세요.

 

[Django, python] Django model

Model 데이터 서비스를 위한 Layer 애플리케이션 내의 models.py 파일에 정의 models.py 파일에 모델 클래스를 만들 수 있다. 모델클래스 1개는 데이터베이스 테이블 1개와 매칭된다. 모델 클래스를 만들

growingegg.tistory.com

 

1. html 파일에 다음 코드를 추가

정적 파일을 사용하기 위해 선언

{% load static %}

css파일 불러오기(html header에 선언)

<link rel="stylesheet" href="{% static 'css/style.css%}">

2. 애플리케이션 디렉토리 안에 static 디렉토리를 생성 

3. static 디렉토리 안에 css 디렉토리 생성  

4. css파일을 디렉토리 안에 생성한다. 

 

tr.header{
  background-color: aqua;
}

tr.record{
  background-color: blue;
}

5. static 파일의 위치를 지정

settings.py에 작성
import os
STATICFILES_DIRS = (
  os.path.join(BASE_DIR, 'static')
)

 

실행결과
CSS 적용 전 모습

 

상세 보기 구현

html 파일 수정, 아이템 이름에 하이퍼 링크 생성 

      {% for item in data %}
        <tr class="record">
          <td align="center">{{item.itemid}}</td>
          <td align="center"><a href="./detail/{{item.itemid}}">{{item.itemname}}</a></td>
          <td align="center">{{item.price}}원</td>
        </tr>
      {% endfor %}

views.py

# detail 함수 생성
def detail(request, itemid):
  # itemid의 값이 itemid인 데이터를 한 개 가져온다. 
  item_detail = item.objects.get(itemid = itemid)
  # detail 파일에 data 변수 전달
  return render(request, 'detail.html', {'data':item_detail})

urls.py 수정

urlpatterns = [
    path('admin/', admin.site.urls),
    path('',views.index),
    path('detail/<int:itemid>',views.detail)
]

detail.html

{% load static %}
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>
<body>
  <div align = "center">
    <h2>상세보기</h2>
    <table>
      <tr><td>{{item_detail.itemid}}</td></tr>
      <tr><td>{{item_detail.itemname}}</td></tr>
      <tr><td>{{item_detail.description}}</td></tr>
    </table>
  </div>
</body>
</html>

 

728x90