2016-03-29 22 views
0

我有我的模板下面的代码:访问与杰基尔/液体模板变量数组

{% for post in site.posts %} 
    {% capture num_colors %}{{ site.colors | size }}{% endcapture %} 
    {% capture color_index %}{{ forloop.index0 | mod: num_colors }}{% endcapture %} 

    <a href="{{ post.url }}" class="post-box" rel="bookmark" title="{{ post.title }}"> 
     <div class="post-block {{ site.colors[color_index] }}"> 
     <div class="contents"> 
      <div class="cat-tag"> 
      {{ post.categories[0] | upcase }} 
      </div> 

      <h2>{{ post.title }}</h2> 
     </div> 
     </div> 
    </a> 
    {% endfor %} 

这使返回什么:即使num_colorscolor_index,并site.colors{{ site.colors[color_index] }}都将返回正确的事当我尝试打印它们时。

颜色在我_config.yml定义为:

colors: [light_blue, coral, yellow, teal, blue, deep_blue]

我使用一个插件来获得模量。基本上我只想为每个帖子添加一个类,当它超过颜色的总数时将重新开始。这看起来很简单,所以我很困惑。

+0

我想这是因为'capture'在变量捕获文本。这可能不适用于数组访问。你可以尝试'分配'索引?但这只是一个猜测,我无法在答案中自己尝试一下。 – michaPau

+0

@michaPau做到了!添加答案,我会接受它 – Evan

回答

0

更换

{% capture num_colors %}{{ site.colors | size }}{% endcapture %} 
{% capture color_index %}{{ forloop.index0 | mod: num_colors }}{% endcapture %} 

由:

{% assign num_colors = site.colors | size %} 
{% assign color_index = forloop.index0 | modulo: num_colors %}