몰입공간

[Django] include로 템플릿 포함시키기 (connected templates with include tag) 본문

Programming/Django

[Django] include로 템플릿 포함시키기 (connected templates with include tag)

sahayana 2022. 2. 2. 10:15


#1.  include tag

 


장고에 템플릿을 연결시키는 방법은 extends 태그말고도 include 태그가 있습니다.

extends는 보통 base 템플릿에 하위 템플릿을 연결시키기 위해 사용하는 반면에,
include는 한 템플릿에 다른 템플릿을 포함시키는 것을 의미합니다.

여기서 중요한 점은 포함시키려는 템플릿 또한 상위 템플릿의 context로 렌더링할 수 있다는 것입니다.

이는 파일 단위로 작업이 가능하기 때문에 협업을 하는 경우 효율적인 작업이 가능합니다.

 

사용법은 다음과 같습니다.

{% include "포함시킬템플릿.html" %}

#2.  예제

 

이전에 실습해본 Tweet 어플리케이션에 한번 적용해보죠.

		<div class="row">
                    {% for tweet in tweets %}
                    <div class="col-md-12">
                        <div class="card">
                            <div class="card-body">
                                '''생략'''
                            
                            <!-- Comment section -->
                            {% include 'tweet/tweet_comment.html' %}
                        {% endfor %}
                </div>

전체 트윗을 노출하는 index 템플릿입니다.

Comment section에 들어갈 form과 comment 리스트를 tweet_comment.html이라는 독립된 템플릿에 넣어주고 include로 삽입하였습니다.

 

 

tweet_comment.html의 내용은 다음과 같습니다.

상위 템플릿의 context를 그대로 쓰고 있습니다.

참고로 view는 따로 건든게 없습니다.

<!-- tweet_comment.html -->

<form class="input-group mb-3" action="{% url 'comment_create' tweet.id %}" method="post">
            {% csrf_token %}
            <input type="text" class="form-control" id='comment' name='comment' placeholder="댓글을 작성 해 주세요"/>
            <button class="btn btn-outline-secondary" type="submit">작성</button>
        </form>
        <hr>
            {% if tweet.comments %}
                {% for comment in tweet.comments.all %}
                    <div class="row">
                        <div class="col-md-12">
                            <div class="media">
                                <div class="media-body">
                                    <h5 class="mt-0"> {{ comment.comment }} </h5>
                                    <span> {{ comment.author.username }} </span>
                                    <span> - {{ comment.created_at | timesince }} 전</span>
                                </div>
                                {% if comment.author == request.user %}
                                    <div style="float: right">
                                        <a href="{% url 'comment_delete' comment.id %}">
                                            <span class="badge bg-danger">삭제</span>
                                        </a>
                                    </div>
                                {% endif %}
                            </div>
                        </div>
                    </div>
                    <hr>
                {% endfor %}
            {% endif %}

성공적으로 렌더링합니다.


 

Comments