Skip to content
This repository

CoTemplate: add FOR loops #741

Closed
trustmaster opened this Issue October 31, 2011 · 6 comments

3 participants

Vladimir Sibirov esclkm Gert Hengeveld
Vladimir Sibirov
Owner

The most requested feature for CoTemplate currently is an ability to use loops in templates that would iterate through arrays. Example:

<ul>
<!-- FOR {KEY}, {VALUE} IN {MY_ARRAY} -->
<li><strong>{KEY}: </strong> {VALUE|htmlspecialchars}</li>
<!-- ENDFOR -->
</ul>

A more simple example:

<ul>
<!-- FOR {VALUE} IN {MY_ARRAY} -->
<li>{VALUE}</li>
<!-- ENDFOR -->
</ul>

Example with associative values:

<ul>
<!-- FOR {KEY}, {VALUE} IN {MY_ARRAY}  -->
<li><strong>{VALUE.title}: </strong> <input name="{KEY}" type="text" value="{VALUE.text|htmlspecialchars}" /></li>
<!-- ENDFOR -->
</ul>

Traditional loop within a range:

<!-- FOR {INDEX} IN {PHP|range(1,10)} -->
  {INDEX}<!-- IF {INDEX} < 10 -->,<!-- ENDIF -->
<!-- ENDFOR -->

Loop from 10 downto 2 with a negative step of -2:

<!-- FOR {NUM} IN {PHP|range(10, 2, -2)} -->
  {NUM}<br />
<!-- ENDFOR -->

Some implementation details:

  • Nesting of BLOCK/IF/FOR is supported without limits.
  • Key and value tags are assigned in global tag scope, there is no block scoping in CoTemplate.
esclkm
Collaborator

why ENDFOR but not ENDFOREACH

Vladimir Sibirov
Owner
esclkm
Collaborator

shorter - make more diffucult for remember - and will makes errors

Gert Hengeveld
Owner

Agree with esclkm, use ENDFOREACH, it makes more sense and its normal PHP behavior.

foreach($a as $k => $v):
  echo $v;
endforeach;

While you're at it, add support for FOR too:

<!-- FOR {I}=1; {I} <= 5; {I}++ -->
  <td id="row{I}">bla</td>
<!-- ENDFOR -->

Alternatively (and probably better), introduce REPEAT:

<!-- REPEAT 5 -->
  <td id="row{I}">bla</td>
<!-- ENDREPEAT -->
Vladimir Sibirov
Owner
Vladimir Sibirov
Owner

I have implemented it in Python-like manner, see the updated issue above for some examples.

Testing is appreciated!

Vladimir Sibirov trustmaster closed this November 11, 2011
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Something went wrong with that request. Please try again.