如何在Twig的“FOR”条件下使用切片

时间:2018-04-02 08:15:26

标签: twig

问题在于切片main_collection,它在执行if条件之前切片所有元素,因此我不能将输出元素的数量限制为1,因为main_collection可能有50- 1000个项目,所以它在这1000个项目中切片导致没有结果,我想仅在if p.header.main_article条件之后应用切片。

{% for p in main_collection|slice(0, 1) if p.header.main_article %}  
    <article class="main-news">
        <a href="{{ p.url }}">
            <h4>{{ p.title }}</h4>
        </a>
    </article>
{% endfor %}

这可能吗?

1 个答案:

答案 0 :(得分:1)

如果您想在纯twig中执行此操作,我不会认为twig无法突破循环,您需要使用类似下面的内容

{% set item = null %}
{% set item_found = false %}

{% for p in main_collection %}
    {% if p.header.main_article and not item_found %}{% set item = p %}{% set item_found = true %}{% endif %}
{% endfor %}

<article class="main-news">
    <a href="{{ item.url }}">
        <h4>{{ item.title }}</h4>
    </a>
</article>

最好延长树枝并创建一个像这样的额外过滤器

    $twig->addFilter(new Twig_SimpleFilter('first_main_article', $main_collection) {
        foreach($main_collection as $p) if ($p->getHeader()->getMainArticle()) return $p;
        return null;
    }

然后在twig

中使用它
{% set item = main_collection | first_main_article %}
{% if item %}
    <article class="main-news">
        <a href="{{ item.url }}">
            <h4>{{ item.title }}</h4>
        </a>
    </article>
{% endif %}

如果你想要多个项目,你应该使用一个数组并调整像这样的代码

{% set items = [] %}
{% for p in main_collection %}
    {% if items|length < 3 and p.header.main_article %}
        {% set items = items|merge([p]) %}
    {% endif %}
{% endfor %}

{% for item in items %}
    <article class="main-news">
        <a href="{{ item.url }}">
            <h4>{{ item.title }}</h4>
        </a>
    </article>      
{% endfor %}
相关问题