Skip to main content

This site requires you to update your browser. Your browsing experience maybe affected by not having the most up to date version.

We've moved the forum!

Please use forum.silverstripe.org for any new questions (announcement).
The forum archive will stick around, but will be read only.

You can also use our Slack channel or StackOverflow to ask for help.
Check out our community overview for more options to contribute.

General Questions /

General questions about getting started with SilverStripe that don't fit in any of the categories above.

Moderators: martimiz, Sean, Ed, biapar, Willr, Ingo, swaiba

Getting iteration number of loop


Go to End


3 Posts   1988 Views

Avatar
AnimalStripe

Community Member, 14 Posts

10 May 2015 at 2:10am

I have a loop within a loop: looping through sub-pages and arrays contained within. Within the inner loop, I'm checking to see if object an position has a bool set to TRUE.

		<% loop $Menu(1) %>
						<% if ClassName = Gallery %>
							<% loop $Children %>
								<% if $isHero %>
									
									THE POS:
									$Pos

									<div class="item">
										<div class="center">
											<a href="$URL"><img  src="$Photograph.Link"  class="full-width img-responsive" alt="" /></a>
										</div>
									</div>

								<% end_if %>
							<% end_loop %>
						<% end_if %>
					<% end_loop %>

So, I only output HTML if the inner condition is met. However, I also want to add a class -- .active -- to the first DIV but as the object is not necessarily the first in its array, I can't use $First or $Pos.

Is there any way to check the iteration of the loop instead of the index of the object?

Avatar
AnimalStripe

Community Member, 14 Posts

10 May 2015 at 4:09am

Edited: 10/05/2015 4:10am

I solved the problem without needing the iteration number:

<div class="active item">
					<% loop $Menu(1) %>
						<% if ClassName = Gallery %>
							<% loop $Children %>
								<% if $isHero %>

										<div class="center">
											<a href="$URL"><img  src="$Photograph.Link"  class="full-width img-responsive" alt="01" /></a>
										</div>
									</div>

									<% if $Last %>
									<% else %>
									<div class="item">
									<% end_if %>

								<% end_if %>
							<% end_loop %>
						<% end_if %>
					<% end_if %

As my first div always has the .active class, I open the div outside of the loop. Then I use a conditional to check whether the item is $Last. If it isn't, I open a new div without the .active class.

Avatar
Pyromanik

Community Member, 419 Posts

11 May 2015 at 11:12pm

Edited: 11/05/2015 11:16pm

Although you've solved this another way, the answer to the original question (Thread title - "Getting iteration number of loop") is $Pos

Also for syntactic sugar, since 3.0 (or there abouts) you do not need an empty if clause to get an else. (<% if $Last %><% else %>output<% end_if %>)
You can simply use the keyword 'not': <% if not $Last %>output<% end_if %>