Twig 如何在细枝'中使用条件后切片;s";至于;

Twig 如何在细枝'中使用条件后切片;s";至于;,twig,Twig,问题在于切片main_collection,如果执行了条件,它会在之前切片所有元素,因此我不能将输出元素的数量限制为1,因为main_collection可能有50-1000个项目,所以它在这1000个项目内切片,不会产生任何结果,我只想在p.header.main\u article条件下应用切片 {% for p in main_collection|slice(0, 1) if p.header.main_article %} <article class="main-n

问题在于切片
main_collection
,如果执行了
条件,它会在
之前切片所有元素,因此我不能将输出元素的数量限制为1,因为
main_collection
可能有50-1000个项目,所以它在这1000个项目内切片,不会产生任何结果,我只想在p.header.main\u 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 %}
{main_集合中p的%s |如果p.header.main_article%}则切片(0,1)
{%endfor%}

这是可能的吗?< /P> < P>如果你想在纯<代码> TWG 中做这件事,我不认为它是“代码> Tigg < /代码>不能脱离循环,那么你就需要使用下面的

之类的东西。
{% 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

{% 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 item=main_collection | first_main_article%}
{%if item%}
{%endif%}

如果您想要多个项目,您应该使用数组并按照如下代码进行调整

    $twig->addFilter(new Twig_SimpleFilter('first_main_article', $main_collection) {
        foreach($main_collection as $p) if ($p->getHeader()->getMainArticle()) return $p;
        return null;
    }
{% 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 %}
{%set items=[]%}
{p在主集合%中的百分比}
{%if items | length<3和p.header.main_article%}
{%set items=items |合并([p])%}
{%endif%}
{%endfor%}
{items%%中的项的%s}
{%endfor%}

So。。你在这里想干什么?您正在尝试仅将项目设置为
主文章
?只需忽略
切片
过滤器,然后尝试显示1个项目,其中
main\u article
设置为true,而不是1000个项目,其中
main\u article
设置为true。不要尝试在纯
twig
中执行此操作。你能扩展小树枝吗?我现在就试试看,不用写扩展了,谢谢!例如,关于如何显示两幅图像,你能不能扩展一下你的答案?@AlexanderKim extended answerty,我无法理解设置为
item
item\u found
的部分-你能解释一下吗?因为你不能在
twig
中打破for循环,所以有必要跟踪你是否找到了符合你要求的项。如果不添加此标志,则标志处于活动状态的最后一项将存储在变量
item
中,而不是第一项