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.

Themes /

Discuss SilverStripe Themes.

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

Is there a way to shorten this code?


Go to End


3 Posts   1531 Views

Avatar
edwardlewis

Community Member, 33 Posts

6 February 2012 at 12:53am


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

Community Member, 33 Posts

6 February 2012 at 9:37am

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

Forum Moderator, 5523 Posts

8 February 2012 at 9:21pm

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