반응형
템플릿에 변수 전달하기
template/hello/index.html을 다음과 같이 수정한다.
<!doctype html>
<html lang="ja">
<head>
<meta charset="utf-8">
<title>{{title}}</title>
</head>
<body>
<h1>{{title}}</h1>
<p>{{msg}}</p>
</body>
</html>
타이틀과 본문에 변수를 지정하였다.
index 수정
hello/views.py의 index함수를 다음과 같이 수정한다.
from django.shortcuts import render
from django.http import HttpResponse
def index(request):
params = {
'title':'Hello/Index',
'msg':'샘플로 작성한 페이지입니다.',
}
return render(request, 'hello/index.html', params)
params배열에 title, msg를 추가하였고 render함수를 보면 params배열을 전달하는 것을 알 수 있다.
여러 개의 페이지 이동
index.html에 링크를 추가하여 동일한 템플릿을 활용하여 index와 next페이지를 작성해본다.
<!doctype html>
<html lang="ja">
<head>
<meta charset="utf-8">
<title>{{title}}</title>
</head>
<body>
<h1>{{title}}</h1>
<p>{{msg}}</p>
<p><a href="{% url link %}">{{link}}</a></p>
</body>
</html>
hello/views.py 수정
from django.shortcuts import render
from django.http import HttpResponse
def index(request):
params = {
'title':'Hello/Index',
'msg':'샘플로 작성한 페이지입니다.',
'link':'next',
}
return render(request, 'hello/index.html', params)
def next(request):
params = {
'title':'Hello/Index',
'msg':'추가로 작성한 페이지입니다.',
'link':'index',
}
return render(request, 'hello/index.html', params)
urlpatterns 수정
hello/urls.py의 urlpatterns배열에 path를 추가한다.
urlpatterns=[
path('', views.index, name='index'),
path('next', views.next, name='next'),
]
https://localhost:8000/hello를 브라우저에 입력하여 index, next페이지를 확인 가능.
반응형
'프로그래밍' 카테고리의 다른 글
| django chap2-7 form송신 (0) | 2022.01.09 |
|---|---|
| django chap2-6 뷰 템플릿 (0) | 2022.01.08 |
| django chap2-4 뷰 템플릿 (0) | 2022.01.08 |
| Linux 개행코드 (0) | 2022.01.06 |
| django chap2-3 뷰 템플릿 (0) | 2022.01.06 |