2016-06-01 51 views
1

为前4个项目设置Drupal 8自定义视图,我希望项目1的布局不同于其余布局。我为自定义视图覆盖了文件,但对于此示例,我使用基本文件保持简单。在树枝节点模板中使用计数器

在意见-view.html.twig基本文件,我们有:

<div class="view-content"> 
    {{ rows }} 
</div> 

在node.html.twig基本文件,我们有:

<div {{ content_attributes.addClass('content') }}> 
    {{ content }} 
</div> 

在node.html.twig我针对这样的事情:

{% if row_counter = 1 %} 
    output this markup/fields 
{% else %} 
    do something boring with the other 3 items. 
{% endif %} 

我能够设置row_counter的意见,view.twig.html文件:

{% for row in rows %} 
    {% set row_counter = loop.index %} 
    <div{{ row.attributes }}> 
     {{ row_counter }} 
    </div> 
{% endfor %} 

但我需要核对的{{row_counter}}在node.html.twig文件中的值....

哪些性能是node.html.twig对证可用它在列表中的位置?

回答

2

documentation

循环变量

Inside of a for loop block you can access some special variables: 
Variable  Description 
----------------------------------------------------------------- 
loop.index  The current iteration of the loop. (1 indexed) 
loop.index0  The current iteration of the loop. (0 indexed) 
loop.revindex The number of iterations from the end of the loop (1 indexed) 
loop.revindex0 The number of iterations from the end of the loop (0 indexed) 
loop.first  True if first iteration 
loop.last  True if last iteration 
loop.length  The number of items in the sequence 
loop.parent  The parent context 

编辑:父模板中的每个变量所知道的是也被称为一个include内的背景是,默认情况下通过。只有宏观的不知道父母的背景下

控制器

<?php 
    require __DIR__ . '/../requires/propel_standalone.php'; 

    echo $twig->render('tests/items.html', [ 
     'items' => [ 
         'Abc', 
         'def', 
         'ghi', 
         'jkl', 
         'mno', 
         'pqr', 
         'stu', 
         'vwx', 
         'z', 
        ], 
    ]); 

items.twig

<!doctype> 
<html> 
    <head><title>Test</title></head> 
    <body> 
     {% for item in items %} 
      {% include "tests/item.html" %} 
     {% endfor %} 
    </body> 
</html> 

item.twig

{% set order = 'Nothing to report' %} 
{% if loop.first %} 
    {% set order = 'I\'m first' %} 
{% endif %} 
{% if loop.last %} 
    {% set order = 'I\'m last' %} 
{% endif %} 

{% if loop.index is even %} 
    {% set order = 'I\'m even' %} 
{% endif %} 

{% if loop.index is divisible by(5) %} 
    {% set order = 'I can be dived by 5' %} 
{% endif %} 

{% if loop.index is divisible by(3) %} 
    {% set order = 'I can be dived by 3' %} 
{% endif %} 


<div> 
    <b>{{ loop.index }}:</b>{{ order }} - {{ item }} 
</div> 
+0

是的,我可以在for循环中访问那些行。 但我需要基于子模板中的loop.index值的逻辑。 –

+0

我不确定..''variable'也可以在包含的'node.twig.html'中找到。你在寻找什么样的逻辑? – DarkBee

+0

是的逻辑是上面的代码块3,我想为项目1编写不同的标记/字段,并为项目2-4做一些不太奢侈的事情。我在view.html.twig中设置了row_count; row_count在node.html.twig中没有值。我在node.html.twig中找不到任何东西给我一个计数器。 –

0

你可以做这样的事情,如果一类是不够的:

您的意见模板:

{% for row in rows %} 
    <div class="{% if loop.index == 1 %}first_element{% endif %}"> 
     {{ row.content }} 
    </div> 
{% endfor %} 

然后就是它的样式适当。