EE Insider Tips
Sponsored by Mijingo's EE 2 Screencasts
ExpressionEngine mini-howtos created by the EE Insider community.
Custom counter for loops that don’t support {count}
Every now and then you might come across a situation where you want to count within a loop but unfortunately the {count} variable is not available.
This is a common problem when dealing with related entries because they are cached internally causing various dynamic statistical variables such as {count} to not be available. The same issue can arise when working with certain plugins that don’t support the use of {count}.
This is easily solved with the use of a little PHP code within your template. In order to use PHP in your template you must first allow PHP (and in this instance set it to parse on OUTPUT) which can be done by editing the template preferences (see EE docs).
Once PHP is enabled, you can count within your loop(s) by creating a variable in PHP and incrementing it within your loop as follows:
{exp:weblog:entries}
<?php $count = 0; ?>
{related_entries id="weblog"}
<?php $count++ ?>
{/related_entries}
{/exp:weblog:entries}
You can then use the variable howeve you like… For example, you could display the count with echo:
{exp:weblog:entries}
<?php $count = 0; ?>
{related_entries id="weblog"}
<?php $count++ ?>
This is loop number <?php echo $count; ?>
{/related_entries}
{/exp:weblog:entries}
Or you could evaluate it to display certain elements at certain points in the loop:
{exp:weblog:entries}
<?php $count = 0; ?>
{related_entries id="weblog"}
<?php $count++ ?>
<?php if ($count==5) echo "This is the fifth entry!"; ?>
{/related_entries}
{/exp:weblog:entries}
Note: If you are worried about enabling PHP for your whole template, you could easily isolate the code block into a seperate template, then enable php on that template, and then embed that template in your main template through .
Email
Print
Post to Twitter
Post to Delicious
Add Your Comment?
You must have an EE Insider account to post comments on Insider Tips. It's fast, easy and hassle-free.
Sign up now (or login).