AI웹 개발자 과정 공부 (팀스파르타)/Django (장고)
24.04.18_TIL (1) (Django Template System)
티아(tia)
2024. 4. 18. 19:56
728x90
++ 장고 공식 문서는 항상 확인하기
https://docs.djangoproject.com/en/4.2/
++ 파이썬 가상환경 실행 끄려면 ctrl + c 누르면 꺼지고 터미널 화면이 돌아옴
1. Templates
- settings.py 에 들어가면 templates 가 있다.
- 장고는 그 안을 뒤적뒤적하면서 필요한 파일을 보여줄 수 있다.
- html 의 다양한 데이터 표현을 위한 다양한 도구를 제공한다.
- 파이썬과 비슷한 데이터표현이지만 장고의 언어로 표현한다. 그것이 바로 DTL(Django Template Language)
1. 변수
{{ variable(내가 쓰고싶은 변수 이름) }}
2. 필터
{{ variable|filter }} # | : 버티컬바
3. 태그
{% if ~ %}
{% endif %}
4. 주석
{# 한 줄 주석 #}
{% comment %}
여러줄
주석
{% endcomment %}
2. hello 의 템플릿을 만들어 표현해보자.
- urls.py 에 path 추가하기
path("hello/", views.hello),
- views.py 에 hello 의 request 추가
def hello(request):
return render(request, "hello.html")
- hello.html 생성해서 ' ! ' 로 추가하기
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Users</title>
</head>
<body>
<h1> hello! tia </h1>
</body>
</html>
3. hello 에서 tia 의 이름을 바꿔보자.
- context 를 넘겨야 한다.
- template에서 사용할 데이터를 view에서 context에 담아 넘긴다.
- DTL의 '변수'를 쓴다.
- views.py 에 hello 에 변수 추가
def hello(request):
context = {
"name":"hwan",
}
return render(request, "hello.html",context)
- hello.html 에서 변수를 넣을 곳에 수정
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Users</title>
</head>
<body>
<h1> hello! {{ name }} </h1>
</body>
</html>
4. hello 에서 다른 변수를 선언해보자.
- views.py 에 hello 에 변수 추가
-
def hello(request): name = 'hwan' tags = ["python","css","html"] books = ['어린왕자', '백설공주'] context = { "name": name, "tags": tags, "books": books, } return render(request, "hello.html",context)
- hello.html 에서 변수를 넣을 곳에 수정
-
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Users</title> </head> <body> <h1> hello! {{ name }} </h1> <p> 첫번째 태그는 {{ tags.0 }} </p> # tags의 0번째 데이터만 가져온다. </body> </html>
5. hello 에서 변수에 '필터'를 넣어보자.
- hello.html 에서 변수에 버티컬을 넣어 대문자로 변형 가능
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Users</title> </head> <body> <h1> hello! {{ name }} </h1> <p> 첫번째 태그는 {{ tags.0 |upper }} </p> # tags의 0번째 데이터에 대문자 변형가능 </body> </html>
6. hello 에서 변수를 여러개 보여주고 싶다.
- hello.html 에서 변수를 여러개 적어주기
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Users</title>
</head>
<body>
<h1> hello! {{ name }} </h1>
<p> 첫번째 태그는 {{ tags.0 |upper }} </p>
<p> 모든 책 목록</p>
<ul>
<li>{{ books.0}}</li>
<li>{{ books.1}}</li>
</ul>
</body>
</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>
<h1> hello! {{ name }} </h1>
<p> 첫번째 태그는 {{ tags.0 |upper }} </p>
<p> 모든 책 목록</p>
<ul>
{% for book in books %} #변수를 태그안에 넣어줌
<li>{{book}}</li>
{% endfor %}
</ul>
</body>
</html>
7. hello , users, index 의 html 의 중복되는 부분을 합쳐서 다른 부분만 보여주고 싶다.
- Template Inheritance 는 중복문제를 해결할 수 있다.
- 코드의 재사용성에 초점이 맞춰져 있고, 상위 템플릿에 공통된 부분을 정의하고 하위 템플릿에서 달라질 부분을 블록(block)으로 만들어 쓸 수 있다.
{% block block_name %}
{% endblock block_name %}
- 상속받는 템플릿에도 표시를 해주어야 한다.
{% extends 'template_name' %}
- templates 에 base.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>
{% block content %} #블록으로 구멍파주기 이 안에만 수정가능하게
{% endblock content %}
</body>
</html>
- hello.html 파일을 수정해준다.
{% extends 'base.html' %}
{% block content %}
<h1> hello! {{ name }} </h1>
<p> 첫번째 태그는 {{ tags.0 |upper }} </p>
<p> 모든 책 목록</p>
<ul>
{% for book in books %}
<li>{{book}}</li>
{% endfor %}
</ul>
{% endblock content %}
정상적으로 잘 작동하는 것을 볼 수 있다.!
8. users, index 도 바꾸어준다.
- index.html
{% extends 'base.html' %}
{% block content %}
<h1> Hello, Django! yaho </h1>
{% endblock content %}
- users.html
{% extends 'base.html' %}
{% block content %}
<h1>users</h1>
{% endblock content %}
9. base.html 의 위치를 바꾸어준다.
- articles 에 있으면 전체적으로 base를 줄 수 없어서 하나 바깥으로 빼서 만들어준다.
- base 의 파일이 상위로 올라갔기 때문에 경로도 바꾸어 주어야 한다.
- settings.py 에서 56번라인에 있는 템플릿츠의 59번째 줄을 바꾸어 주어야 한다. 여기서 부터 찾으라고..
다시 잘 동작한다.!!
반응형