问题描述:

I'm looking to display information from a csv file on a jekyll-generated site. I need to search for the appropriate category in the csv file, then display four of them on the page. Filtering to the selected category is no problem, but I'm having difficulty limiting the output to four.

Is there a way to apply a limit to an if statement? Or is there any other way to write this? I'm not that savvy in Liquid, so it's extremely likely that I'm missing an obvious solution.

Basic code to make all the applicable data show up on the screen:

 {% for study in site.data.studies %}

{% if study.category contains "foo" %}

<div class="col-sm-3">

<h3>{{ study.title }}</h3>

<div class="list-of-attributes">

<h6>Attributes: </h6>

{{ study.attributes }}

</div>

</div>

{% else %}

{% continue %}

{% endif %}

{% endfor %}

I've also tried unless and tablerow, neither of which worked at all. Am I at least on the right track? How can I limit this forloop to stop at four items?

Thank you!

网友答案:

Ideally data should be filtered before rendering however you can also create a variable in liquid to hold the number of stuff rendered

{% assign rendered = 0 %}

{% for study in site.data.studies %}
  {% if study.category contains "foo" %}
      <div class="col-sm-3">
        <h3>{{ study.title }}</h3>
        <div class="list-of-attributes">

          <h6>attributes: </h6>
          {{ study.attributes }}
        </div>
      </div>

    {% assign rendered = rendered | plus: 1 %}
    {% if rendered == 4 %}
      {% break %}
    {% endif %}

  {% endif %}
{% endfor %}

The ideal solution as I said would be to create your own filter which does all the work (filter by category and limit the number of results)

{% assign filtered = site.data.studies | my_custom_filter %}
{% for study in filtered %}
  <div class="col-sm-3">
    <h3>{{ study.title }}</h3>
    <div class="list-of-attributes">
      <h6>attributes: </h6>
      {{ study.attributes }}
    </div>
  </div>
{% endfor %}
网友答案:

Presuming that your category is a string, not an array, you can do :

{% assign selected = site.data.studies | where: 'category','foo' %}
{% for study in selected limit:4 %}
  <div class="col-sm-3">
    <h3>{{ study.title }}</h3>
    <div class="list-of-attributes">
      <h6>Attributes: </h6>
      {{ study.attributes }}
    </div>
  </div>
{% endfor %}

And if your category is a string like "foo, bar, baz" or and array of strings you can use the jekyll 3.2 where_exp filter like this :

{% assign selected = site.data.studies | where_exp:"item", "item.category contains 'foo'" %}
相关阅读:
Top