Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP

Loading…

CoTemplate: add FOR loops #741

Closed
trustmaster opened this Issue · 6 comments

3 participants

@trustmaster
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.
@trustmaster trustmaster was assigned
@esclkm
Collaborator

why ENDFOR but not ENDFOREACH

@trustmaster
Owner
@esclkm
Collaborator

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

@ghengeveld
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 -->
@trustmaster
Owner
@trustmaster
Owner

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
Something went wrong with that request. Please try again.