如何在Symfony2中使用Twig制作3列表

Mkf*_*two 3 pagination html-table symfony twig

我是Twig和Symfony2的新手.我想知道如何用Twig创建一个3列表.我的数据来自数据库

到目前为止,我已经尝试了一切,但仍然没有效果.我在Stackoverflow上发现了这个关于制作一个2列表的问题,除了我之外它完美无缺.我想要3列.

<table>
  {% for var in var1 %}
    {% if (loop.index % 2) %}<tr>{% endif %}
    <td>
      <div class="bloc">
        <a href="{{ path('xxxxxxx', {'id':var.id}) }}">
        <span>{{ var.name}}  </spann></a></div>
        <img src="{{ asset(var.image ) }}"  />    
      </div>
    </td>
    {% if (loop.index % 2) and loop.last %}
      <td>&nbsp</td>
    {% endif %}
    {% if (loop.index0 % 2) or loop.last %}</tr>{% endif %}
  {% endfor %}
</table>


ex: var1  contains names and pictures from database.
name1  name2  name3
name4  name5  name6
...
Run Code Online (Sandbox Code Playgroud)

这就是我的ATM

name1   name2
name3   name4   name5
name6   name7   name8
Run Code Online (Sandbox Code Playgroud)

Ale*_*lin 5

我的解决方案适用于任意数量的列:

{% set columns = 3 %}
{% for name in names %}
    {% if loop.first or loop.index0 is divisibleby(columns) %}
        <tr>
    {% endif %}

    <td>{{ name }}</td>

    {% if loop.last and loop.index is not divisibleby(columns) %}
        {% for n in range(low=columns - (loop.index % columns), high=1, step=-1) %}
            <td>&nbsp;</td>
        {% endfor %}
    {% endif %}
    {% if loop.last or loop.index is divisibleby(columns) %}
        </tr>
    {% endif %}
{% endfor %}
Run Code Online (Sandbox Code Playgroud)


小智 5

正确的方法是使用batch(array_chunk):

{% for batchResults in result.items|batch(result.total_results / columns) %}
    <div class="{{cycle(['left', 'left', 'right'], loop.index)}}">
        {% for item in batchResults %}
            <div class="{% if loop.last %}last{% endif %}">
                {{item}}
            </div>
        {% endfor %}
    </div>
{% endfor %}
Run Code Online (Sandbox Code Playgroud)