Clean comma separated list created in a fluid template for TYPO3 with iteration.

Sometimes you need a comma separated list in a Fluid template for TYPO3 that doesn't have a comma at the end. I show you a simple method to create such a list from records passed to your template by TypoScript or an Extbase controller.

Why would you need this type of list?

There are countless examples where you need comma separated lists. For example, when outputting categories under a blog headline, or even in the middle of a text, as exemplified here: Apple, Banana, Tomato, Pear, Cherry, and so on.

In the code I show you with 4 simple examples up to the inline code and how to implement this with the fluid template engine of TYPO3.

Example Code

<!-- Bad example, has comma at the end -->
<f:for each="{products}" as="product">
  {product.title},
</f:for>

<!-- Complicated version. Works but has too much code -->
<f:for each="{products}" as="product" iteration="i">
  <f:if condition="!{i.isLast}">
    <f:then>
      {product.title},
    </f:then>
    <f:else>
      {product.title}
    </f:else>
  </f:if>
</f:for>

<!-- Good example, only set the comma when it's not the last loop! -->
<f:for each="{products}" as="product" iteration="i">
  {product.title}<f:if condition="!{i.isLast}">, </f:if>
</f:for>

<!-- One line only with inline notation of f:for viewhelper -->
{f:if(condition: '{i.isLast} != 1', then: '{p.title}, ', else: '{p.title} ') -> f:for(each: '{products}', as: 'p', iteration: 'i')}

Comments

No Comments

Write comment

* These fields are required