[TIL] Flask 대댓글 template 구현

Funnystyle·2021년 4월 7일
0

노마드 코더에서 Flask template 챌린지를 하다가 대댓글을 구현하는 걸 좀 검색해봤다. 그냥 첫번째 댓글만 보여주면 챌린지는 통과하는 수준이었으나, 이놈의 집요함이 또 발동했다.

Flask 의 template 에는 macro 기능이 있다. 이걸 이용하면 된다.

일단 comment.html은 아래와 같다. 잘 보면 show_comment 를 안쪽에서 재귀적으로 호출하는 것을 볼 수 있다.

{% macro show_comment(comments) %}
  {% for comment in comments %}
     
     ...
     
    {% if comment.children|length > 0 %}
      <div style="padding-left: 20px;">
        {{ show_comment(comment.children) }}
      </div>
    {% endif %}
    
  {% endfor %}
{% endmacro %}

이제 이 template 을 갖다 쓸 파일은 다음과 같이 만들면 된다.

{% from "comment.html" import show_comment with context %}
<!DOCTYPE html>
<html>
<head>
</head>

<body>
  {% if post.children|length > 0 %}
    {{ show_comment(post.children) }}
  {% endif %}
</body>

</html>

첫째줄에서 import 하는게 중요하고, {{ }} 안에서 호출하면 된다.

참고:
https://stackoverflow.com/questions/60254511/is-there-a-generic-recursive-flask-template
https://uniwebsidad.com/libros/explore-flask/chapter-8/creating-macros
https://stackoverflow.com/questions/24163579/length-of-string-in-jinja-flask

profile
polyglot

0개의 댓글