Python/Django

템플릿(Template) & 실습

yunajoe 2022. 10. 7. 08:30

템플릿 상속 실습

templates/app/base.html 

<!DOCTYPE html>
<html lang="ko">
<head>
    <meta charset="UTF-8">
    <title>오늘도화이팅</title>
</head>

<body>
    <h1>Django 입문</h1>
    {% block content %}
    {% endblock %}
    <hr />
    &copy; 2022. 오늘도 화이팅 
</body>
</html>
templates/app/index.html

# 상속받기전 
<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<body>
    <h1>PostList</h1>  
       {% for post in post_list %}
        <div>
        {{ post.id }} : {{ post.title}}
        </div>
    {% endfor %}
</body>
</html>

# 상속 받은 후 

{% extends "app/base.html" %}
{% block content %}
     {% for post in post_list %}
        <div>
        {{ post.id }} : {{ post.title}}
        </div>
    {% endfor %}
{% endblock %}
# 상속 받기 전 
<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<body>
    <h1>포스트제목:{{ post.title }} </h1>
    <h2>내용:{{ post.content }} </h2>
</body>
</html>

# 상속 받은 후 

{% extends 'app/base.html'%} }
{% block content %}
     <h1>포스트제목:{{ post.title }} </h1>
      <h2>내용:{{ post.content }} </h2>
{% endblock %}

http://127.0.0.1:8000/app/

 

 

http://127.0.0.1:8000/app/1

# a href 링크를 걸어보자 

urls.py 


urlpatterns = [
    path("admin/", admin.site.urls),
    path("app/", views.index),
    path("app/<int:pk>/", views.post_detail),
]


# index.html 
{% extends "app/base.html" %}
{% block content %}
     {% for post in post_list %}
        <div>
            <a href="/app/{{ post.id }}/">
                {{ post.id }} : {{ post.title}}
            </a>
        </div>
    {% endfor %}
{% endblock %}

# post_detail.html
{% extends 'app/base.html'%} }
{% block content %}
      <h2>포스트제목:{{ post.title }} </h2>
      <h2>내용:{{ post.content }} </h2>
      <hr/>
      <a href="/app/">목록으로</a>
{% endblock %}