Ruby的液体模板引擎中的模数(或缺乏模数)

And*_*rew 22 ruby cycle liquid jekyll

我正在Jekyll网站上工作,我正在尝试输出嵌套在行div中的三个列div.Liquid使用他们的cycle过滤器非常容易:

{% for p in site.categories.post %}
    {% cycle 'add rows': '<div class="row">', nil, nil %}
        <div class="column">
            <a href="{{ p.url }}">{{ p.title }}</a>
        </div>
    {% cycle 'close rows': nil, nil, '</div>' %}
{% endfor %}
Run Code Online (Sandbox Code Playgroud)

但是,只有当有3个,6个,9个等帖子时,这才真正有用.当帖子的总数不是三的倍数时,<div class="row">永远不会关闭 - for循环在结束标记作为close rows循环的一部分输出之前结束.

在Ruby,PHP或任何其他语言中,我可以使用模数运算符轻松修复此问题,因此除了close rows循环我将输出</div>if site.categories.size % 3 == 0.但是,Liquid,因为它是一种安全的模板语言,不支持模数.

<div class="row">当帖子总数不是三的倍数时,我还能做些什么来正确关闭?

Deh*_*hli 14

我发现这种方式很棒!

{% assign mod = forloop.index0 | modulo:4 %}
{% if mod == 0 %}
   <!-- Do stuff -->
{% endif %}
Run Code Online (Sandbox Code Playgroud)


小智 13

对于您的具体示例,您可以在使用{% cycle 'close rows': nil, '</div>', '</div>' %}之后使用{% endfor %}.


Ryt*_*ius 8

目前唯一的方法是编写一个液体过滤器来实现这一目标.在适当的代码中的某处注册过滤器(如果使用rails而不使用它们,则位于不同的位置).

液体:: Template.register_filter(LiquidFilters)

在您的项目/ lib目录中添加liquid_filters.rb:

module LiquidFilters  
  # makes modulus operation available to templates
  def mod(data, param)
    data % param
  end  
end
Run Code Online (Sandbox Code Playgroud)

之后,您可以像在模板中一样使用它:{{variable | mod:5}}

如果您需要将它用于某些逻辑,您可以捕获该值.

{% capture modulus %}{{ variable | mod:5 }}{% endcapture %}
Run Code Online (Sandbox Code Playgroud)

只是我注意到捕获的值是一个字符串,所以为了比较你使用的

{% if modulus == "0" %}
 ..
{% endif %}
Run Code Online (Sandbox Code Playgroud)