Cycle - Cycle over an array of elementsIf you want to iterate over an array of values within a loop you can now use the cycle statement. This is useful when you want to colour code alternate rows of a table. There are two ways in which you can use the cycle statement:
- Code: Select all
{% for a from 1 to 10 %}
{{a}} : {% cycle ['a', 'b', 'c'] %}<br />
{% endfor %}
{% set cycleElements as ['a', 'b', 'c', 'd'] %}
{% for a from 1 to 10 %}
{{a}} : {% cycle using cycleElements %}<br />
{% endfor %}
The first lets you assign the array within the call to cycle while the other lets you make use of an already defined array of values. The two examples will output the following when called:
- Code: Select all
1 : a
2 : b
3 : c
4 : a
5 : b
6 : c
7 : a
8 : b
9 : c
10 : a
1 : a
2 : b
3 : c
4 : d
5 : a
6 : b
7 : c
8 : d
9 : a
10 : b
The compiled versions of the code will look similar to this:
- Code: Select all
// Using inline array
<?php $doo_view_basic_1267324709 = range(1, 10, 1);
if (!empty($doo_view_basic_1267324709)):
foreach($doo_view_basic_1267324709 as $data['a']):
?>
<?php echo DooViewBasic::is_set_or($data['a']); ?> :
// Cycle starts here
<?php
if (!isset($doo_view_basic_1267324710))
$doo_view_basic_1267324710 = array('a','b','c');
echo current($doo_view_basic_1267324710);
if (next($doo_view_basic_1267324710)===false)
reset($doo_view_basic_1267324710);
?>
// Cycle ends here
<br />
<?php endforeach;
endif; ?>
// Using a preset array for cycle
<?php $data['cycleElements'] = array('a','b','c','d'); ?>
<?php $doo_view_basic_1267324711 = range(1, 10, 1);
if (!empty($doo_view_basic_1267324711)):
foreach($doo_view_basic_1267324711 as $data['a']):
?>
<?php echo DooViewBasic::is_set_or($data['a']); ?> :
// Cycle starts here
<?php
echo current($data['cycleElements']);
if (next($data['cycleElements'])===false)
reset($data['cycleElements']);
?>
// End cycle here
<br />
<?php endforeach;
endif; ?>
Note that cycle will always assume that the array to be cycled exists (safe mode does not work here as the next, current and reset functions do not work if it is). From a performance perspective its faster if you can define your array outside of the loop and make use of the 'using' keyword.
For a better example usage see the original request for this feature. Please note that the compiled code is different to that presented in the original request.
viewtopic.php?f=9&t=1068&start=0
Note: code samples my not be 100% accurate.