【问题标题】:How to group a collection in Liquid?如何在 Liquid 中对集合进行分组?
【发布时间】:2012-10-27 00:23:35
【问题描述】:

我有一个 Jekyll 应用程序(使用 Liquid),我想知道如何在 Liquid 中将一组项目组合成一个小的集合子集。

例如,假设我有这个数组:

fruits = ['apples', 'oranges', 'bananas', 'pears', 'grapes']

我真正想做的是,在 Liquid 页面中,得到这个:

fruit_groups = [['apples', 'oranges'], ['bananas', 'pears'], ['grapes', null]]

例如,Ruby on Rails 可以通过附加到可枚举的 .group_by 方法来做到这一点。

我可以在 Liquid 中执行此操作吗?

用例:我有大量项目,但我需要将它们转换为 <ul> 元素的列。所以,如果我有三列,我需要得到三个子集合。

谢谢!

【问题讨论】:

    标签: jekyll liquid


    【解决方案1】:

    这并不能直接回答您的问题,但我不确定您是否想做您所描述的事情(而且我很确定您不能) - Liquid 是一个模板系统,而​​不是一种成熟的编程语言。我怀疑您将能够使用一些 for 循环和循环功能来实现您的最终目标:http://code.google.com/p/liquid-markup/wiki/UsingLiquidTemplates

    例如:

    <ul>
    {% for fruit in fruits %}
        {% capture pattern %}{% cycle 'odd_class', 'even_class' %}{% endcapture %}
            <li class={{ pattern }}>{{ fruit }}</li>
    {% endfor %}
    </ul>
    

    <ul class="odd">
    {% for fruit in fruits %}
        {% capture pattern %}{% cycle 'odd', 'even' %}{% endcapture %}
        {% if pattern == 'odd' %}
            <li>{{ fruit }}</li>
        {% endif%}
    {% endfor %}
    </ul>
    
    <ul class="even">
    {% for item in fruits %}
        {% capture pattern %}{% cycle 'odd', 'even' %}{% endcapture %}
        {% if pattern == 'even' %}
            <li>{{ fruit }}</li>
        {% endif%}
    {% endfor %}
    </ul>
    

    如果您有三列,那么您的循环中只有三个步骤,并且您的 if 语句中有三个方向。

    如果一切都失败了,您可以编写一个插件(在 Ruby 中),它会在数据到达模板层之前对其进行重构,但我怀疑这会有点矫枉过正。

    【讨论】:

      猜你喜欢
      • 2012-11-14
      • 1970-01-01
      • 2022-10-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-01-04
      • 1970-01-01
      相关资源
      最近更新 更多