我可以在模板中呈现产品类别列表。但是类别列表没有按字母顺序显示。如何按字母顺序渲染它们?
修改
我使用以下代码来呈现类别和子类别。
<ul class="cd-accordion-menu animated">
{% for tree_category, info in tree_categories %}
<li {% if info.has_children %}class="has-children"
{% else %}{% endif %}>
{% if info.has_children %}
<input type="checkbox" name="{{ tree_category.name|lower }}"
id="{{ tree_category.name|lower }}">
<label for="{{ tree_category.name|lower }}">{{ tree_category.name|safe }}
{% else %}
<a href="{{ tree_category.get_absolute_url }}">{{ tree_category.name|safe }}</a>
{% endif %}
{% if info.has_children %}</label>{% endif %}
{% if info.has_children %}
<ul>
{% endif %}
{% for n in info.num_to_close %}
</ul>
</li>
{% endfor %}
{% endfor %}
</ul>
答案 0 :(得分:1)
我有相同的要求,最后自定义了category_tree模板标签。我复制了category_tree的原始实现(请参阅link)并添加了排序步骤以进行排序。与原始的category_tree模板标记相比,只有一个内衬发生了变化。
from django import template
from oscar.core.loading import get_model
register = template.Library()
Category = get_model('catalogue', 'category')
@register.assignment_tag(name="category_tree")
def get_annotated_list(depth=None, parent=None):
"""
Gets an annotated list from a tree branch.
Borrows heavily from treebeard's get_annotated_list
"""
# 'depth' is the backwards-compatible name for the template tag,
# 'max_depth' is the better variable name.
max_depth = depth
annotated_categories = []
start_depth, prev_depth = (None, None)
if parent:
categories = parent.get_descendants()
if max_depth is not None:
max_depth += parent.get_depth()
else:
categories = Category.get_tree()
info = {}
# CUSTOM SORTING HERE
for node in sorted(categories, key=lambda x: x.name):
node_depth = node.get_depth()
if start_depth is None:
start_depth = node_depth
if max_depth is not None and node_depth > max_depth:
continue
# Update previous node's info
info['has_children'] = prev_depth is None or node_depth > prev_depth
if prev_depth is not None and node_depth < prev_depth:
info['num_to_close'] = list(range(0, prev_depth - node_depth))
info = {'num_to_close': [],
'level': node_depth - start_depth}
annotated_categories.append((node, info,))
prev_depth = node_depth
if prev_depth is not None:
# close last leaf
info['num_to_close'] = list(range(0, prev_depth - start_depth))
info['has_children'] = prev_depth > prev_depth
return annotated_categories
PS:如果您不知道如何包含自定义模板标签,请检查django文档,它们需要进入专用文件夹。
模板代码:
<ul class="cd-accordion-menu animated">
{% for tree_category, info in tree_categories %}
<li {% if info.has_children %}class="has-children"
{% else %}{% endif %}>
{% if info.has_children %}
<input type="checkbox" name="{{ tree_category.name|lower }}" id="{{ tree_category.name|lower }}">
<label for="{{ tree_category.name|lower }}">{{ tree_category.name|safe }}</label>
{% else %}
<a href="{{ tree_category.get_absolute_url }}">{{ tree_category.name|safe }}</a>
{% endif %}
{% if info.has_children %}
<ul>
{% else %}
</li>
{% endif %}
{% for n in info.num_to_close %}
</ul>
</li>
{% endfor %}
{% endfor %}
</ul>