How Would You Make A Two Column Table With Twig?

前端 未结 3 1305
渐次进展
渐次进展 2021-02-05 07:30

I can\'t for the life of me figure out how to add a every OTHER iteration in a Twig loop.

For instance:

$numArray = a         


        
相关标签:
3条回答
  • 2021-02-05 07:52

    For this specific case you can prepare your array before. So in a loop you will have in each row two variables. Try first example from this site http://twig.sensiolabs.org/doc/templates.html

    0 讨论(0)
  • 2021-02-05 07:53

    The proper way of doing this is using the batch filter. It is new in 1.12.3.

    <table>
    {% for row in numArray|batch(2) %}
      <tr>
      {% for column in row %}
        <td>{{ column }}</td>
      {% endfor %}
      </tr>
    {% endfor %}
    </table>
    

    Ref: http://twig.sensiolabs.org/doc/filters/batch.html

    0 讨论(0)
  • 2021-02-05 08:16

    Something like this would work:

    <table>
      <tr>
      {% for num in numArray %}
          <td>
            {{num}}
          </td>
      {% if loop.index is even %}
        </tr>
        <tr>
      {% endif %}
      {% endfor %}
    
      {% if num|length is odd %}
        <td></td>
      {% endif %} 
      </tr>
    </table>
    

    An alternative way, that feels much less hacky:

    <table>
      {% for i in range(0, numArray|length-1, 2) %}
      <tr>
        <td>{{ numArray[i] }}</td>
        <td>{{ numArray[i+1]|default("") }}</td>
      </tr>
      {% endfor %}
    </table>
    
    0 讨论(0)
提交回复
热议问题