TIL & Todo List/Coding for Entrepreneures

Day-5(forloop.counter, custom template tags)

navill 2020. 1. 17. 21:03

Category Template - {{ forloop.counter|divisibleby:<number> }}

forloop.counter: for loop안에서 반복 횟수에 따라 번호를 출력

<div class="col-sm-3">
        <div class="list-group">
            {% for item in object_list%}
            <a href="{{ item.get_absolute_url }}" class="list-group-item list-group-item-action">
                {{ forloop.counter }} - {{ item.title }}</a>

            {% if forloop.counter|divisibleby:2 %}
                </div></div><div class="col-sm-3"><div class="list-group">
            {% endif %}

            {% endfor %}
        </div>
</div>
  • {% if forloop.counter|divisibleby:2 %}: counter의 숫자가 divisibleby에 할당된 숫자로 나뉘어 떨어질 경우 True
    • 새로운 "list-group"을 추가한다.

동일한 기능을 'cycle' tag를 이용해 구현할 수 있다.

# 화면에 나타내고 싶은 col이 4개 일 경우 
{% cycle '' '' '' '</div></div><div class="col-sm-3"><div class="list-group">'%}
# 화면에 나타내고 싶은 col이 3개 일 경우 
{% cycle '' '' '</div></div><div class="col-sm-3"><div class="list-group">'%}
# 화면에 나타내고 싶은 col이 2개 일 경우 
{% cycle '' '</div></div><div class="col-sm-3"><div class="list-group">'%}

 

 

 

Annotate - Django: annotate

 

 

Custom Template Tag for Video render

  • 동영상을 재생하기 위한 template tag를 생성한다.

  • Category, Video 등 여러 앱에서 재사용할 수 있다.
# videos/templatetags/render_video.py
from django import template

from videos.models import Video

# template tag에 등록하기 위한 데코레이터
register = template.Library()  

@register.inclusion_tag('videos/snippets/render_video.html')
def render_video(video_obj):
    video = None
    if isinstance(video_obj, Video):
        video = video_obj.embed_code
    return {'video': video}


# lecture_detail.html
{% load render_video %}

...

# render_video에 object.video를 전달한다.
{% render_video object.video %}
  • @register로 커스텀 태그 함수(render_video)를 감싸야 {% load %} tag를 이용해 태그 함수를 사용할 수 있다.

 

@register.inclusion_tag  - Django: inclusion_tags()

  • 다른 템플릿을 렌더링하고 이를 템플릿 태그로 사용할 때 inclusion_tags를 사용한다.
    • 예를 들어 버튼 기능을 담은 탬플릿(button.html)을 탬플릿 태그로 지정
    • @register.inclusion_tag(button.html)... def button(args): ... return {'args': args}
    • 다른 탬플릿에서 {% load button %} 태그를 이용해 button.html에서 제공하는 버튼 기능을 사용할 수 있다.

 

 

 

 

이후 과정부터는 django의 쓰임새보다 프로젝트의 구조를 디테일하게 설계하는 내용을 담고 있다. 모델과 객체들이 복잡하게 얽혀있어서 글로 설명하기가 어려울 것 같고 추가적인 내용을 덧붙이기에 시간이 너무 많이 걸릴 것 같아 포스트 작성은 여기까지 할 예정이다. Srvup 프로젝트를 따라 하면서 복잡한 모델 관계를 형성하고 template이나 view에서 해당 객체를 불러올 때 prefetch_related의 사용법과 중요성을 알 수 있었다. 코드를 전체적으로 다시 한번 천천히 살펴보면서 놓친 부분이나 제대로 이해하지 못한 부분이 있는지 살필예정이다