Chunk ViewHelper <f:chunk>
The ChunkViewHelper splits an array or a string into chunks of the given size. The last chunk may be shorter if the items or characters can't be divided evenly.
For arrays, this ViewHelper mimicks PHP's array_ function.
For strings, it mimicks PHP's mb_ function, so the size
counts characters, not bytes.
Iterators like generators can yield the same key more than once. All of
their items are used, unless preserve is set: then only the last
item per key is used, like with PHP's iterator_ function.
Examples
Split an array into chunks
Given items = :
<f:chunk value="{items}" size="2" />
[
['a', 'b'],
['c', 'd'],
['e'],
]
Preserve the original array keys
Given scores = :
<f:chunk value="{scores}" size="2" preserveKeys="{true}" />
[
['a' => 1, 'b' => 2],
['c' => 3],
]
Render items in rows
<f:for each="{items -> f:chunk(size: 2)}" as="row">
<div class="row"><f:for each="{row}" as="item"><span>{item}</span></f:for></div>
</f:for>
<div class="row"><span>a</span><span>b</span></div>
<div class="row"><span>c</span><span>d</span></div>
<div class="row"><span>e</span></div>
Split a string into groups
Given iban = 'DE89370400440532013000':
{iban -> f:chunk(size: 4) -> f:join(separator: ' ')}
DE89 3704 0044 0532 0130 00
Go to the source code of this ViewHelper: ChunkViewHelper.php (GitHub).
Arguments
The following arguments are available for the chunk ViewHelper:
preserveKeys
-
- Type
- boolean
- Default
- false
If true, the keys of the original array are preserved in each chunk. Otherwise each chunk is reindexed numerically. Has no effect on strings.
size
-
- Type
- integer
- Required
- 1
Number of items or characters in each chunk. The last chunk may be shorter.
value
-
- Type
- mixed
The array or string to split into chunks