1

I'm working with a carousel that has two rows. Each item in the carousel displays an icon for a "media partner". This works all fine and dandy until there's an odd number of media partners, because then there is an extra unnecessary space in the carousel. I have the issue solved logically, but I can't figure out how to implement it into Craft. I need a way to access a certain entry plainly by its number, i.e. the fifth entry, seventh entry, ninth entry, etc.

There are 11 entries that I am working with, however that number may change in the future. So, first, I grab how many current entries there are in the particular field that I am looking for:

{% set entryNum = craft.entries.section('partners').featuredMediaPartner('1') | length %}

This returns 11.

Next, this number gets divided by two, because I want to display the middle partner in the empty space that the carousel creates if there's an odd number (I already have coded to determine what to do if there's an odd number). So 11/2 = 5. How would I access the fifth entry? Thanks.

1

I don't know whether you've seen the batch Twig filter? You may find if useful to accomplish exactly what you are trying to do, but with a little bit less hassle.

From the example in the link above:

{% set items = ['a', 'b', 'c', 'd', 'e', 'f', 'g'] %}

<table>
{% for row in items|batch(3, 'No item') %}
    <tr>
        {% for column in row %}
            <td>{{ column }}</td>
        {% endfor %}
    </tr>
{% endfor %}
</table>

And here's what it outputs:

<table>
    <tr>
        <td>a</td>
        <td>b</td>
        <td>c</td>
    </tr>
    <tr>
        <td>d</td>
        <td>e</td>
        <td>f</td>
    </tr>
    <tr>
        <td>g</td>
        <td>No item</td>
        <td>No item</td>
    </tr>
</table>

Essentially you're grouping your values into rows of a specific number (in this example it's 5). Then you can specify what to put in any empty spaces. So here it's the words 'No Item', but in your case it could be the middle partner entry.

0

If you have a array of entries like so:

{% set entries = craft.entires.find() %}

And you wanted to access the fifth item in the array (which is 0-indexed), you would do something like:

{% set fifthEntry = entries[4] %}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.