高级循环使用?

时间:2012-07-31 18:46:15

标签: ruby jekyll liquid

我正在试图弄清楚如何正确使用Liquid的cycle和html blelow。这是一个永无止境的行,最多3列(float:left)布局。

<!-- row -->
<div class="single-post-container">
   <div class="single-post-item">
      <div class="single-post-head">
         <a href="{{ post.url }}" />
         <h6>{{ post.title }}</h6>
      </div>
   </div>
   <div class="single-post-item">
      <div class="single-post-head">
         <a href="{{ post.url }}" />
         <h6>{{ post.title }}</h6>
      </div>
   </div>
   <div class="single-post-item">
      <div class="single-post-head">
         <a href="{{ post.url }}" />
         <h6>{{ post.title }}</h6>
      </div>
   </div>
</div>
<!-- row -->
<div class="single-post-container">
   <div class="single-post-item">
      <div class="single-post-head">
         <a href="{{ post.url }}" />
         <h6>{{ post.title }}</h6>
      </div>
   </div>
   <div class="single-post-item">
      <div class="single-post-head">
         <a href="{{ post.url }}" />
         <h6>{{ post.title }}</h6>
      </div>
   </div>
   <div class="single-post-item">
      <div class="single-post-head">
         <a href="{{ post.url }}" />
         <h6>{{ post.title }}</h6>
      </div>
   </div>
</div>

我能够用这个丑陋的东西让它半工作({{ post.title }}字面上显示而不是实际的标题):

{% for post in site.posts %}

   column {%cycle '<div class="single-post-container"><div class="single-post-item"><div class="single-post-head"><a href="{{ post.url }}" /><h6>{{ post.title }}</h6></div></div>', '<div class="single-post-item"><div class="single-post-head"><a href="{{ post.url }}" /><h6>{{ post.title }}</h6></div></div>', '<div class="single-post-item"><div class="single-post-head"><a href="{{ post.url }}" /><h6>{{ post.title }}</h6></div></div></div>'%}

{% endfor %}

请帮忙!也许有更好的方法?

1 个答案:

答案 0 :(得分:1)

cycle标记中的字符串未被处理,因此不会发生液体替换(这就是{{ post.title }}字面意思的原因)。

更好的方法可能是:

{% for post in site.posts %}
  {% cycle '<div class="single-post-container">', '', '' %}
  <div class="single-post-item">
    <div class="single-post-head">
      <a href="{{ post.url }}" />
      <h6>{{ post.title }}</h6>
    </div>
  </div>
  {% cycle '', '', '</div> %}
{% endfor %}

仅循环开始和结束标记。请注意,如果帖子数不是3的倍数,则会中断(div打开)。

基于以上原因,更好的解决方案可能是:

{% for post in site.posts %}
  {% capture mod_three %}{{ forloop.index0 | modulo: 3 }}{% endcapture %}
  {% if mod_three == '0' %}
    <div class="single-post-container">
  {% endif %}
      <div class="single-post-item">
        <div class="single-post-head">
          <a href="{{ post.url }}" />
          <h6>{{ post.title }}</h6>
        </div>
     </div>
  {% if mod_three == '2' or forloop.last %}
     </div>
  {% endif %}
{% endfor %}

这(理论上我还没有测试过)如果帖子的数量不是3的倍数(这就是or forloop.last正在测试的那个),就不会让div打开。

Here is some documentation关于特殊forloop变量及其属性。)