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.

Upgrading SilverStripe /

Ask questions about upgrading SilverStripe to the latest version.

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

SS3.1 Choice between multiple Loops or breaking out of loop for a variable


Reply


2 Posts   510 Views

Avatar
MartinPhone

Community Member, 57 Posts

14 March 2014 at 1:06pm

Edited: 14/03/2014 1:09pm

So, whether or not this was the best way, I had this in a widget: ("output" returned a Page which has a 'Preview Text' variable in it. )

<span class="crossSellImg">

   <% control output %>
      <a href="$Link">
      $Thumbnail</a>
</span>

<span class="crossSellText">
   <a href="$Link"><h1>$Title</h1></a>
   <% end_control %>
   
   <% if CrossSellContent %>
      <p>$CrossSellContent</p>
   <% else %>
   
   <% control output %>
      <p>$PreviewText</p>   
   <% end_if %>
   
      <p><a href="$Link">Read more</a></p>
   <% end_control %>

</span>

Which meant that if this "CrossSellContent" was anything but null, it'd display that, which belongs to the Widget instance itself rather than the page it links to.

Just replacing the "controls" with "loops" or "withs" doesn't work as it gives SSTemplateParseException - unknown open block "loop".

So it sounds like you can only have one <% loop blah %> per ss?

My rubbish solution is

<span class="crossSellImg">

<% if CrossSellContent %>
   <% loop output %>
      <a href="$Link">$Thumbnail</a>
</span>
<span class="crossSellText">
   <a href="$Link"><h1>$Title</h1></a>
   <% end_loop %>   
   <p>$CrossSellContent</p>
   
<% else %>   
   
   <% loop output %>
      <a href="$Link">$Thumbnail</a>
</span>
<span class="crossSellText">
   <a href="$Link"><h1>$Title</h1></a>
      
   <p>$PreviewText</p>   
   <% end_loop %>

<% end_if %>
   
   <p><a href="$Link">Read more</a></p>
</span>

Which just feels totally stupid and repetitive. The best solution would be to somehow break out of the loop, check to see whether this variable exists, print out the relevant variable (of the widget or of the target page) and move on to the closing code.

Can anyone guide the amateur here?

Avatar
Willr

Forum Moderator, 5513 Posts

23 March 2014 at 6:25pm

You can have as many loop tags nested as you want but they have to be ended in the order you opened. If you need to get 'out' of a loop to check for a previous value try using $Up. You can also use $Top to go all the way up to the original object.