Ad

Get Blog Post From Postlist Array October Cms?

- 1 answer

I am creating a blog page, the post list page is in the form of different sized images. I need to be able to style each post list item individually so need to be able to access the post list array with twig and get posts.

So for example, when accessing a featured image from a post you can use:

    post.featured_images[0].path

I would like to do this but to select the first post in list of posts.

Ad

Answer

Whatever you want to do with the first post you can access the first post using the iteration variable in the loop.

There are few iteration variables in Twig, I usually use loop.index variable. For example:

{% for post in posts %}

    {% if loop.index == 1 %}
        {{ post.title }}
        {# this is the first post title #}
    {% else %}
        {{ post.title }}
        {# this is others posts title #}
    {% endif %}

{% endfor %}

And as you go if loop.index == 2 so you can access the second post. If it equals 3 you can access the third post etc.

Another alternative would be loop.first.

{% if loop.first %}
{# It goes here if it's the first record of the loop #}
{% endif %}
{% if loop.last %}
{# It goes here if it's the last record of the loop #}
{% endif %}

To learn more about Twig's loop variables: http://twig.sensiolabs.org/doc/2.x/tags/for.html#the-loop-variable

Ad
source: stackoverflow.com
Ad