CoTemplate: add FOR loops #741

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

3 participants

@trustmaster
Cotonti member

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.
@trustmaster trustmaster was assigned Oct 31, 2011
@esclkm
Cotonti member

why ENDFOR but not ENDFOREACH

@trustmaster
Cotonti member
@esclkm
Cotonti member

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

@ghengeveld
Cotonti member

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 -->
@trustmaster
Cotonti member
@trustmaster trustmaster added a commit that referenced this issue Nov 11, 2011
@trustmaster trustmaster Implemented #741 FOR loops in CoTemplate. Please see updated issue #741
… for syntax examples.
833f62a
@trustmaster
Cotonti member

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

Testing is appreciated!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment