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.

Themes

Discuss SilverStripe Themes.

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

Is there a way to shorten this code?


Reply

3 Posts   553 Views

Avatar
edwardlewis

6 February 2012 at 12:53am Community Member, 32 Posts

I'm creating a site which has a series of boolean fields to control what icons are displayed on a page.. in total there will be around 20 fields for this particular section.

In my template I have something like this:

<% if Field1 %>
   <img src="$ThemeDir/images/icon/Field1.jpg" title="SField1" alt="$Field1" width="32" height="32"/>
<% end_if %>
<% if Field2 %>
   <img src="$ThemeDir/images/icon/Field2.jpg" title="SField2" alt="$Field2" width="32" height="32"/>
<% end_if %>
<% if Field3 %>
   <img src="$ThemeDir/images/icon/Field3.jpg" title="SField3" alt="$Field3" width="32" height="32"/>
<% end_if %>
<% if Field4 %>
   <img src="$ThemeDir/images/icon/Field4.jpg" title="SField4" alt="$Field4" width="32" height="32"/>
<% end_if %>

Can that be re-rwriiten to something shorter?

Avatar
edwardlewis

6 February 2012 at 9:37am Community Member, 32 Posts

I've realised that the alt tags and title tags in that won't work, eg they will just display "1" values.

Would still be interested if there was a way to reduce the code?

Avatar
Willr

8 February 2012 at 9:21pm Forum Moderator, 5511 Posts

Group all the fields into 1 DataObject set via a PHP function. Something like

function FieldsForPage() {
$output = new DataObjectSet();

for($i = 1; $i < 10; $i++) {
$field = "Field$i";
if($this->$field) $output->push(new ArrayData(array('Field' => $this->$field)));
}
return $output;
}

<% control FieldsForPage %>
<img src="$ThemeDir/images/icon/$Field.jpg" title="$Field" alt="$Field" width="32" height="32"/>
<% end_control %>