Symfony - 如何在Twig模板的循环中省略第一个项目?

9
我希望能在不显示第一条新闻的情况下展示新闻。我该如何实现这个目标?
以下是需要修改的代码:
<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>

你尝试过使用 |slice 吗? - Robert
4个回答

14

罗伯特建议的更简洁的版本如下:

{% for item in news[1:] %}

1
您可以将您的非常简短的答案作为评论发送。 - Saeid Amini

7

您可以使用 slice 过滤器,其类似于 PHP 中的 array_slice() 函数。

{% for item in news[1, news.length -1 ] %}

5
在您的循环中添加此代码以跳过第一条新闻
{% if loop.index0 > 0 %}
 {# display your news #}
{% endif %}

4
冗长翻译:如果不是循环的第一个元素,那么执行以下操作:简洁翻译:若非首个循环元素,则执行如下操作: - Mike Doe

0
当然还有另一个答案,可能更加干净/简单/或其他什么的 - 在第一时间不要将行传递给Twig。

这是最好的答案。不要写hack,修复你的破玩意儿。 - Mike Doe
1
我不知道它是否是最好的答案,我想这取决于上下文...也许你需要那一行在其他地方使用,例如... - zak

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接