YUYANE

Django / 장고 템플릿 태그 사용해서 url 연결 하기 본문

Framework/DJANGO

Django / 장고 템플릿 태그 사용해서 url 연결 하기

YUYA 2021. 1. 20. 15:13

학습 강의

www.udemy.com/course/python-and-django-full-stack-web-developer-bootcamp/

 

 

 

Relative URLs with Templates장고 템플릿 태그 사용해서 url 연결 하기

 

템플릿은 유저에게 보여줄 화면이 html 파일로 구성되어 있다.

보통 웹사이트는 여러 개의 페이지로 이루어져 있고, 각 페이지끼리 서로 연결 되어 있다.

이 때, url 경로를 하드 코딩으로 직접 입력할 수도 있지만, 장고의 템플릿 언어를 사용하면 훨씬 편하다!

 

 

전체 디렉토리 구성

 

 

크게 프로젝트 폴더(learning_templates), 앱 폴더(basic_app), 템플릿 폴더(templates) 세 가지 폴더가 있다.

템플릿 폴더 안에는 공통 페이지(base.html)와 나머지 페이지를 나타내는 파일들로 구성되어 있다.

 

 

basic_app/views.py

from django.shortcuts import render

# Create your views here.
def index(request):
    return render(request,'basic_app/index.html',context_dict)

def other(request):
    return render(request,'basic_app/other.html')

def relative(request):
    return render(request,'basic_app/relative_url_templates.html')

각 요청에 따라 이동할 경로를 연결하는 메서드를 작성한다. 

 

 

learning_templates/urls.py

from django.contrib import admin
from django.urls import path
from basic_app import views
from django.conf.urls import include

urlpatterns = [
    path('admin/', admin.site.urls),
    path('',views.index,name='index'),
    path('basic_app/',include('basic_app.urls')),
]

basic_app 폴더의 views.py를 import 하고, urlpatterns을 작성한다.

 

path('',views.index,name='index'),

url 뒤에 아무 것도 붙지 않았을 때 views.py 파일의 index 함수를 호출하라는 뜻이다.

기본 페이지를 호출하는 경로가 되겠다.

 

path('basic_app/',include('basic_app.urls')),

url 뒤에 'basic_app'이 붙었다면, basic_app 폴더에 있는 urls.py 파일로 가라는 의미이다.

 

 

basic_app/urls.py

from basic_app import views
from django.urls import path
#TEMPLATE TAGGING
app_name = 'basic_app'

urlpatterns= [
    path('relative/',views.relative,name='relative'),
    path('other/',views.other,name='other'),
]

'basic_app'에 추가로 다른 단어(relative, other)들이 붙었을 때, 이동할 페이지를 안내하는 경로들이다.

urlconf 파일에서 app_name 변수를 따로 정의해주면 후에 url name을 찾을 때 중복을 방지할 수 있다.

 

 

templates/basic_app/relative_url_templates.html

<!DOCTYPE html>
<html lang="en" dir="ltr">
  <head>
    <meta charset="utf-8">
    <title></title>
  </head>
  <body>
    <h1>WELCOME TO RELATIVE URL TEMPLATES</h1>
    <a href="{% url 'basic_app:other' %}">The other page</a>
    <a href="{% url 'admin:index' %}">Link To Admin</a>
    <a href="{% url 'index' %}">Link To Index</a>
  </body>
</html>

url 주소 뒤에 'basic_app/relative'가 붙었을 때 도착할 html 파일이다.

 

{% tag %}

참고 : docs.djangoproject.com/en/3.1/ref/templates/language/#variables

 

장고에서 이렇게 생긴 문법을 사용하면, 문자를 생성해낼 수도 있고, 어떤 로직을 돌릴수도 있다.

장고는 24가지의 빌트인 템플릿 태그를 가지고 있는데, 더 자세히 알고 싶다면 아래 장고 문서에 잘 설명되어 있다.

docs.djangoproject.com/en/3.1/ref/templates/builtins/#ref-templates-builtins-tags

 

{% url 'name' %}

'url'을 입력하고 뒤에 이동 할 페이지의 'name'을 입력하면 해당 페이지로 이동한다.

 

 

 

http://127.0.0.1:8000/basic_app/relative/

 

해당 url 주소를 입력하고 보이는 화면. 설정해준대로 링크가 잘 연결되어 있다!

 

Comments