【问题标题】:Symfony - How can I omit the first item in a twig template's loop?Symfony - 如何省略树枝模板循环中的第一项?
【发布时间】:2016-10-20 12:14:48
【问题描述】:

我想在没有第一个的情况下显示新闻。我怎样才能做到这一点?

这是我必须更改的代码:

<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吗?

标签: php symfony twig


【解决方案1】:

Robert 的建议有更简洁的版本:

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

【讨论】:

  • 您可以将非常简短的回答作为评论发送。
【解决方案2】:

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

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

【讨论】:

    【解决方案3】:

    把它放在你的循环中以省略第一条新闻

    {% if loop.index0 > 0 %}
     {# display your news #}
    {% endif %}
    

    【讨论】:

    • 详细一点:{% if not loop.first %}
    【解决方案4】:

    当然还有另一个答案可能/可能不会更清洁/更简单/w/e - 首先不要将行传递给 Twig。

    【讨论】:

    • 这是最好的答案。不要写黑客,修好你的**。
    • 我不知道它是否是最佳答案,我想这取决于上下文...也许您在其他地方需要该行...
    猜你喜欢
    • 1970-01-01
    • 2012-07-27
    • 2013-08-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-06
    • 1970-01-01
    相关资源
    最近更新 更多