Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Symfony - How can I omit the first item in a twig template's loop?

Tags:

php

twig

symfony

I want to display news without first one. How I can achieve this?

Here is code I have to change:

<div class="home-box-news carousel-news slide home-box-shadow" id="news" style="clear: both;">
    <ol class="carousel-indicators news-box">

    {% for i in 0..news|length-1 %}
        {% if loop.index is not divisibleby (2) %}
            <li data-target="#news" data-slide-to="{{ i / 2 }}" {% if loop.first %}class="active"{% endif %}></li>
        {% endif %}
    {% endfor %}

    </ol>
    <div class="carousel-inner">
    {% for item in news %}
        {% if loop.index is not divisibleby (2) %}
            <div class="item{% if loop.first %} active{% endif %}">
            <div class="carousel-caption">
        {% endif %}
            <h3><a href="{{ path('home_news_index') }}">{{ item.name }}</a></h3>
            <p class="date">{{ item.createdAt|date('d.m.Y, G:i') }}</p>
            <p {% if loop.index is divisibleby (2) %}style="border-bottom: 0;" {% endif %}>{{ item.content[:110]|nl2br }}{% if item.content|length > 110 %}... <a class="more" href="{{ path('home_news_index') }}">czytaj dalej</a>{% endif %}</p>
        {% if loop.index is divisibleby (2) or loop.last %}
            </div>
            </div>
        {% endif %}
    {% endfor %}
    </div>
</div>
like image 676
George Pennet Avatar asked Oct 20 '16 12:10

George Pennet


3 Answers

There is more concise version of what Robert suggested:

{% for item in news[1:] %}
like image 77
Lubomir Avatar answered Oct 03 '22 07:10

Lubomir


You can use slice filter which works like array_slice() function in PHP.

{% for item in news[1, news.length -1 ] %}
like image 32
Robert Avatar answered Oct 03 '22 06:10

Robert


put this in your loop to omit first news

{% if loop.index0 > 0 %}
 {# display your news #}
{% endif %}
like image 20
Yannis Berrouag Avatar answered Oct 03 '22 07:10

Yannis Berrouag