首页 > 解决方案 > 如何在鹡鸰模型中拆分菜单?

问题描述

我正在尝试创建一个导航菜单,当菜单中的对象数量甚至在菜单的两半之间放置一个图像时。这是我尝试在我的菜单模型和模板中使用来创建效果的代码。

"""Splitting the menu in half for the frontend."""
    @property
    def is_even(self):
        if (self.objects.count() % 2) == 0:
            return True
        else:
            return False
    
    @property
    def find_halves(self):
        first_half = self.objects[0:self.objects.count()/2]
        second_half = self.objects[self.objects.count()/2:self.objects.count()]
        return first_half, second_half
    <nav class="main-nav">

        {% image navigation.logo fill-115x115 as logo %}
            
        <ul class="nav-links">
        {% if navigation.is_even %}
            {% for item in navigation.menu_items.first_half.all %}
            <li><a href="{{ item.link }}" {% if item.open_in_new_tab %} target="_blank" {% endif %}>{{ item.title }}</a></li>
            {% endfor %}
            <img src="{{ logo.url }}" alt="CCCR Logo" class="logo"> 
            {% for item in navigation.menu_items.second_half.all %} 
            <li><a href="{{ item.link }}" {% if item.open_in_new_tab %} target="_blank" {% endif %}>{{ item.title }}</a></li>
            {% endfor %} 
        {% else %}
            <img src="{{ logo.url }}" alt="CCCR Logo" class="logo"> 
            {% for item in navigation.menu_items.all %}
            <li><a href="{{ item.link }}" {% if item.open_in_new_tab %} target="_blank" {% endif %}>{{ item.title }}</a></li>
            {% endfor %}
        {% endif %} 
        </ul>
    </nav>

但是,当我运行代码时,即使我在 wagtail 管理员中有六个菜单项,它也会转到 else 语句。

标签: djangowagtail

解决方案


对于像这样与用户看到的内容相关的项目,我建议使用 Django 模板标签divisiblebyhttps ://docs.djangoproject.com/en/3.0/ref/templates/builtins/#divisibleby

所以也许是这样的:

{% if navigation.menu_items.count|divisibleby:"2" %}

您可能还会发现cycle模板标签很有用。通过在奇数项和偶数项上交替放置一个类,它可以让你做你想要的布局。


推荐阅读