Предлагаю вашему вниманию небольшой снипет, который мы написали, когда понадобилось сделать вывод объектов по колонкам.
-
from django import template
-
-
-
register = template.Library()
-
-
-
class SplitObjectsNode(template.Node):
-
def __init__(self, objects, list):
-
self._objects = template.Variable(objects)
-
self._list = list
-
-
def render(self, context):
-
import math
-
columns_count = len(self._list)
-
objects = self._objects.resolve(context)
-
-
for item in self._list:
-
context[item] = []
-
-
if len(objects) == 0:
-
return ”
-
-
dec = float(len(list(objects))) / columns_count
-
mid = int(math.ceil(dec))
-
pass_part = len(list(objects)) % columns_count
-
count_full_cols = columns_count – pass_part
-
-
idx = 0
-
index = 0
-
for item in self._list:
-
step = mid
-
if idx >= pass_part and pass_part != 0:
-
step = mid – 1
-
context[item] = objects[index: step + index]
-
index += step
-
idx += 1
-
return ”
-
-
-
@register.tag
-
def split_objects(parser, token):
-
"""
-
Split content of the objects to equal parts. Number of parts is a count of passed arguments to tag.
-
-
Example:
-
{% split_objects objects col1 col2 col3 %}
-
<table><tr><td>
-
{% for item in col1 %} {{ item.title }} {% endfor %}
-
</td><td>
-
{% for item in col2 %} {{ item.title }} {% endfor %}
-
</td><td>
-
{% for item in col3 %} {{ item.title }} {% endfor %}
-
</td></tr></table>
-
"""
-
parts = token.contents.split()
-
if len(parts) < 3:
-
raise template.TemplateSyntaxError, "Tag should get at the least 3 arguments. Example usage is {% split_objects objects col1 col2 %}"
-
-
tagname = parts.pop(0)
-
objects = parts.pop(0)
-
return SplitObjectsNode(objects, parts)
