【问题标题】:Jekyll and Liquid for-loopJekyll 和 Liquid for 循环
【发布时间】:2015-06-17 08:51:10
【问题描述】:

我想为页面导航创建一个小侧导航。 该网站包含多个图像,一个在另一个之上,导航位于每个图像内,并链接到各个 ID。

我正在使用带有液体模板引擎的 jekyll。为了不对每个元素进行硬编码,我创建了一个 for 循环,它获取单独 .yml 文件的数据。

它应该是这样的:

Image

我的问题是它不适用于第一个元素。在第一个导航元素内,应该选择第一个圆圈。但它不是:

Image

这是代码:

{% for element in site.data.elements %}
{% capture number %}{{ forloop.length }}{% endcapture %}
<section id="spezial-{{forloop.index}}" {% assign imgIndex = {{forloop.index0}} %} class="spezial-img" style="background-image:url('{{ element.bild }}');">
    <div class="container spezial-container">
        <div class="sub-navi">
            <ul>
                {% for y in (1..number) %}
                    {% if imgIndex == naviIndex %}
                        <li><a href="#spezial-{{forloop.index}}" {% assign naviIndex = {{forloop.index}} %} {{ naviIndex }} class="active" ><i class="fa fa-dot-circle-o"></i></a></li>
                    {% else %}
                        <li><a href="#spezial-{{forloop.index}}" {% assign naviIndex = {{forloop.index}} %}><i class="fa fa-circle-o"></i></a></li>
                    {% endif %}
                {% endfor %}
            </ul>
        </div>
    </div>
</section>
{% endfor %}

【问题讨论】:

  • 请您解释一下anzahlnaviIndex
  • 我更正了“anzahl”,它是数据文件中元素的数量。 “naviIndex”是液体辅助变量的一个变量,它显示了当前迭代的索引

标签: html for-loop navigation jekyll liquid


【解决方案1】:

您正在比较两个工作方式不同的计数器。

{% assign imgIndex = {{forloop.index0}}

这将从 0 计数到 array.size-1

{% assign naviIndex = {{forloop.index}}

这将从 1 计数到 array.size

由于您不在同一个“时区”,因此对于您拥有的第一张图片

imgIndex == naviIndex
0 == 1 -> false

然后,从第二个循环开始,在每个循环中有一次你会达到相等,但不是在正确的元素上。

例如,在第二个imgIndex 元素上,活动类将设置在第一个naviIndex 元素上,但这是错误的。以下所有元素都是一样的。

正确的代码可以是:

{% for element in site.data.elements %}
{% capture number %}{{ forloop.length }}{% endcapture %}
{% assign imgIndex = {{forloop.index}} %}
<section id="spezial-{{imgIndex}}" class="spezial-img" style="background-image:url('{{ element.bild }}');">
    <div class="container spezial-container">
        <div class="sub-navi">
            <ul>
                {% for naviIndex in (1..number) %}
                    {% if imgIndex == naviIndex %}
                      <li><a href="#spezial-{{forloop.index}}" %} {{ naviIndex }} class="active" ><i class="fa fa-dot-circle-o"></i></a></li>
                    {% else %}
                        <li><a href="#spezial-{{forloop.index}}" {% assign naviIndex = {{forloop.index}} %}><i class="fa fa-circle-o"></i></a></li>
                    {% endif %}
                {% endfor %}
            </ul>
        </div>
    </div>
</section>
{% endfor %}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-03-16
    • 1970-01-01
    • 2018-12-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多