Jekyll使用JSON数据文件生成导航出现重复输出问题求助
This isn't a Jekyll bug—it's just a difference in how Liquid (Jekyll's templating engine) handles iterations over hash objects compared to Jinja2. Let's break down what's happening and how to fix it.
The Root Cause
Your JSON navigation file is a hash (key-value pairs), but your current loop structure doesn't account for how Liquid iterates over hashes:
- When you write
{% for rubrik in site.data.navigation %}, eachrubrikis an array containing two elements: the key (like"home") and its corresponding value object (withname,path,icon). - Then your inner loop
{% for part in rubrik %}iterates over both elements of that array. The first iteration uses the string key (which has nopathoriconproperties), creating an empty/garbage navigation item. The second iteration uses the actual value object, creating the correct item. That's why you're seeing duplicates.
The Fix
Use Liquid's key-value iteration syntax to directly access each navigation entry without the extra loop. Here's the corrected template:
<div class="navbar-menu"> <div class="navbar-start"> {% for key, item in site.data.navigation %} <a class="navbar-item{% if page.url == item.path %} is-active{% endif %}" href="{{ item.path }}"> <span class="icon"><i class="{{ item.icon }}"></i></span> <span>{{ item.name }}</span> </a> {% endfor %} </div> </div>
How It Works
{% for key, item in site.data.navigation %}loops through each key-value pair in your JSON.keywill be"home","faq", etc., anditemwill be the corresponding object with all your navigation data.- You no longer need the inner loop—you can directly use
item.name,item.path, anditem.iconto build your navigation links.
This will generate only the correct navigation items without any duplicates or empty entries.
内容的提问来源于stack exchange,提问作者brillenheini
相关产品推荐
相关产品推荐

