장고 템플릿을 사용하여 트리 구조 (재귀)를 렌더링하려면 어떻게해야합니까?
Django 템플릿을 사용하여 HTML로 렌더링하려는 메모리에 트리 구조가 있습니다.
class Node():
name = "node name"
children = []
일부 개체가있을 것이다 root이다 Node,하고 children의 목록입니다 Node들. root템플릿의 내용에 전달됩니다.
나는 이것이 어떻게 성취 될 수 있는지에 대한 토론을 발견 했지만, 포스터는 이것이 생산 환경에서 좋지 않을 수 있다고 제안합니다.
아무도 더 나은 방법을 알고 있습니까?
정식 대답은 "하지 마십시오"라고 생각합니다.
대신해야 할 일은 뷰 코드의 내용을 풀기위한 것이므로 템플릿에서 (| de) dents를 반복하는 문제 일뿐입니다. 트리를 순환하면서 목록에 들여 쓰기와내어 쓰기를 추가 한 다음 해당 "여행"목록을 템플릿에 보내는 방식으로 할 수있을 것 같습니다. (그런 다음 템플릿은 해당 목록 을 삽입 <li>하고 </li>"이해"하는 재귀 구조를 만듭니다.)
또한 템플릿 파일을 재귀 적으로 포함하는 것이 정말 잘못된 방법이라고 확신합니다.
with템플릿 태그를 사용하여 트리 / 재귀 목록을 작성할 수 있습니다.
샘플 코드 :
기본 템플릿 : 'all_root_elems'가 하나 이상의 트리 루트 목록이라고 가정합니다.
<ul>
{%for node in all_root_elems %}
{%include "tree_view_template.html" %}
{%endfor%}
</ul>
tree_view_template.html 중첩 렌더링 ul, li및 사용 node은 아래로 템플릿 변수 :
<li> {{node.name}}
{%if node.has_childs %}
<ul>
{%for ch in node.all_childs %}
{%with node=ch template_name="tree_view_template.html" %}
{%include template_name%}
{%endwith%}
{%endfor%}
</ul>
{%endif%}
</li>
이것은 당신이 필요로하는 것보다 훨씬 더 많을 수 있지만, 'mptt'라는 django 모듈이 있습니다. 이것은 SQL 데이터베이스에 계층 적 트리 구조를 저장하고 뷰 코드에 표시 할 템플릿을 포함합니다. 거기에서 유용한 것을 찾을 수있을 것입니다.
여기에 링크가 있습니다 : django-mptt
나는 당신의 모든 너무 많은 불필요한 사용) 너무 늦었 와 태그, 이것은 내가 recuesive을 수행하는 방법이다 :
기본 템플릿에서 :
<!-- lets say that menu_list is already defined -->
<ul>
{% include "menu.html" %}
</ul>
그런 다음 menu.html에서 :
{% for menu in menu_list %}
<li>
{{ menu.name }}
{% if menu.submenus|length %}
<ul>
{% include "menu.html" with menu_list=menu.submenus %}
</ul>
{% endif %}
</li>
{% endfor %}
예, 할 수 있습니다. 파일 이름을 변수로 {% include %}에 전달하는 것은 약간의 트릭입니다.
{% with template_name="file/to_include.html" %}
{% include template_name %}
{% endwith %}
Django에는이 정확한 시나리오를위한 템플릿 도우미가 내장되어 있습니다.
https://docs.djangoproject.com/en/dev/ref/templates/builtins/#unordered-list
나는 같은 문제가 있었고 템플릿 태그를 작성했습니다. 나는 이와 같은 다른 태그가 있다는 것을 알고 있지만 어쨌든 사용자 정의 태그를 만드는 법을 배워야했습니다 :) 꽤 잘 나온 것 같습니다.
사용법 지침은 독 스트링을 읽으십시오.
github.com/skid/django-recurse
이것을 수정하십시오 :
root_comment.html
{% extends 'students/base.html' %}
{% load i18n %}
{% load static from staticfiles %}
{% block content %}
<ul>
{% for comment in comments %}
{% if not comment.parent %} ## add this ligic
{% include "comment/tree_comment.html" %}
{% endif %}
{% endfor %}
</ul>
{% endblock %}
tree_comment.html
<li>{{ comment.text }}
{%if comment.children %}
<ul>
{% for ch in comment.children.get_queryset %} # related_name in model
{% with comment=ch template_name="comment/tree_comment.html" %}
{% include template_name %}
{% endwith %}
{% endfor %}
</ul>
{% endif %}
</li>
예를 들어-모델 :
from django.db import models
from django.contrib.auth.models import User
from django.utils.translation import ugettext_lazy as _
# Create your models here.
class Comment(models.Model):
class Meta(object):
verbose_name = _('Comment')
verbose_name_plural = _('Comments')
parent = models.ForeignKey(
'self',
on_delete=models.CASCADE,
parent_link=True,
related_name='children',
null=True,
blank=True)
text = models.TextField(
max_length=2000,
help_text=_('Please, your Comment'),
verbose_name=_('Comment'),
blank=True)
public_date = models.DateTimeField(
auto_now_add=True)
correct_date = models.DateTimeField(
auto_now=True)
author = models.ForeignKey(User)
아무도 dicts를 좋아하지 않습니까? 여기에 뭔가 빠졌을 수도 있지만 메뉴를 설정하는 가장 자연스러운 방법 인 것 같습니다. 키를 항목으로 사용하고 값을 링크로 사용하면 DIV / NAV에 표시되고 멀리 이동합니다!
기지에서
# Base.html
<nav>
{% with dict=contents template="treedict.html" %}
{% include template %}
{% endwith %}
<nav>
이것을 불러
# TreeDict.html
<ul>
{% for key,val in dict.items %}
{% if val.items %}
<li>{{ key }}</li>
{%with dict=val template="treedict.html" %}
{%include template%}
{%endwith%}
{% else %}
<li><a href="{{ val }}">{{ key }}</a></li>
{% endif %}
{% endfor %}
</ul>
그것은 기본값을 시도하지 않았거나 아직 주문한 적이 있습니까?
비슷한 문제가 있었지만 먼저 JavaScript를 사용하여 솔루션을 구현 한 후 곧 장고 템플릿에서 동일한 작업을 수행 할 방법을 고려했습니다.
I used the serializer utility to turn a list off models into json, and used the json data as a basis for my hierarchy.
ReferenceURL : https://stackoverflow.com/questions/32044/how-can-i-render-a-tree-structure-recursive-using-a-django-template
'Program Club' 카테고리의 다른 글
| MySQL에 UTF-8 MB4 문자 (ios5의 이모티콘)를 삽입하는 방법은 무엇입니까? (0) | 2021.01.05 |
|---|---|
| 라우터 탐색은 동일한 페이지에서 ngOnInit를 호출하지 않습니다. (0) | 2021.01.05 |
| Chrome 확장 코드 대 콘텐츠 스크립트 대 삽입 된 스크립트 (0) | 2021.01.05 |
| Unix에서 경로의 일부 제거 (0) | 2021.01.05 |
| 난독 화 된 코드에서 문자열 숨기기 (0) | 2020.12.31 |