CoTemplate: add FOR loops #741

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

Projects

None yet

3 participants

@trustmaster
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
Member
esclkm commented Oct 31, 2011

why ENDFOR but not ENDFOREACH

@trustmaster
Member

It's just shorter

2011/10/31 esclkm
reply@reply.github.com:

why ENDFOR but not ENDFOREACH

Reply to this email directly or view it on GitHub:
#741 (comment)

@esclkm
Member
esclkm commented Oct 31, 2011

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

@ghengeveld
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
Member

OK, accepted. Thanks guys!

2011/10/31 Gert Hengeveld
reply@reply.github.com:

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

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

Reply to this email directly or view it on GitHub:
#741 (comment)

@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
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