Data Story

데이터 사이언스, 쉽게 설명하기

Web/Django

Django 템플릿(2) 변수

_data 2023. 3. 5. 13:59

Python 객체 뷰에서 템플릿으로 정보를 보내는 방법을 알아보자.

https://qorskawls12.tistory.com/68

 

Django 템플릿

일반적인 전체 프로젝트에 대한 싱글 템플릿 폴더가 아니라, 관련 애플리케이션을 기반으로 템플릿 폴더 또는 디렉토리를 분리하고자 한다. 앱별로 템플릿 디렉토리를 분리하는 것이 더 이상적

qorskawls12.tistory.com

에 이어서 한다.

 

1. templates/first_app 하위 파일로 variables.html을 생성하자.

2. first_app/views.py에서 아래의 코드를 작성한다.

from django.shortcuts import render
# Create your views here.

def example(request):
    return render(request, 'first_app/example.html')

def variables(request):
    return render(request, 'first_app/variables.html')

3. first_app/urls.py 에서 아래의 코드를 작성한다.

from django.urls import path
from . import views

urlpatterns= [
    path('',  views.example),
    path('variables/', views.variables)
]

 

 

 

이제 변수를 지정해서 값을 사용해볼 것이다. 그러려면 Key-value 형식으로 지정해주어야 한다.

 

4. first_app/views.py에서 아래의 코드를 추가로 작성한다.

from django.shortcuts import render
# Create your views here.

def example(request):
    return render(request, 'first_app/example.html')

def variables(request):

    vars = {'ST':"SON",
            'MF':"LEE",
            'DF':'KIM'
    }

    return render(request, 'first_app/variables.html', context=vars)

우리가 사용할 변수는 vars이다.

 

5. templates/first_app에 있는 variables.html에 아래와 같이 입력한다.

<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <h1>Variables!</h1>
    <p>In korea, the most best player ST is {{ST}} , MF is {{MF}}, DF is {{DF}}.</p>
</body>
</html>

장고 템플릿 언어는 {{}} 형식으로 사용한다.

만약, SON을 소문자로 표현하고 싶다면, {{ST | lower}} 로 하면 소문자로 표현된다. 이외에도 capfirst, center 등이 있다.

https://docs.djangoproject.com/en/4.1/ref/templates/builtins/

 

Django

The web framework for perfectionists with deadlines.

docs.djangoproject.com

 

'Web > Django' 카테고리의 다른 글

Django 템플릿 태그와 url명  (0) 2023.03.05
Django 템플릿(3) 명령어  (0) 2023.03.05
Django 템플릿  (0) 2023.03.05
Django ResponseNotFound & 404 페이지  (0) 2023.03.03
Django 동적 뷰(라우팅)  (0) 2023.03.03