django - 如何在鹡鸰模型中拆分菜单?
问题描述
我正在尝试创建一个导航菜单,当菜单中的对象数量甚至在菜单的两半之间放置一个图像时。这是我尝试在我的菜单模型和模板中使用来创建效果的代码。
"""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 语句。
解决方案
对于像这样与用户看到的内容相关的项目,我建议使用 Django 模板标签divisibleby
: https ://docs.djangoproject.com/en/3.0/ref/templates/builtins/#divisibleby
所以也许是这样的:
{% if navigation.menu_items.count|divisibleby:"2" %}
您可能还会发现cycle
模板标签很有用。通过在奇数项和偶数项上交替放置一个类,它可以让你做你想要的布局。
推荐阅读
- vue.js - Vue-router 在切换 rutes 时一次渲染两个组件
- php - 接受带有条件的 URL 路径的正则表达式
- node.js - Mongoose/MongoDB 增加了两倍,我不知道为什么
- android - java.lang.IllegalStateException:Facebook 提供程序未配置
- typescript - 无法使用 Chrome DevTools 调试 Typescript 文件 - 未“链接到源映射”
- html - 如果网页没有移动版本,我应该设置哪个元视口标签?
- audio - 通过css或js隐藏html5音频标签上的volumeControl
- yii - 试图找到一个不存在 Yii2 的文件
- python - 解决 HTTP 错误 400:在 Google Chrome 中使用工作链接的错误请求
- c++ - 如何处理具有未知数量参数的用户函数以进行性能测量?