Jump to:

1382 Posts in 491 Topics by 521 members

Themes

SilverStripe Forums » Themes » Is there a way to shorten this code?

Discuss SilverStripe Themes.

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

Page: 1
Go to End
Author Topic: 537 Views
  • edwardlewis
    Avatar
    Community Member
    32 Posts

    Is there a way to shorten this code? Link to this post

    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?

  • edwardlewis
    Avatar
    Community Member
    32 Posts

    Re: Is there a way to shorten this code? Link to this post

    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?

  • Willr
    Avatar
    Forum Moderator
    5497 Posts

    Re: Is there a way to shorten this code? Link to this post

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

    537 Views
Page: 1
Go to Top

Want to know more about the company that brought you SilverStripe? Then check out SilverStripe.com

Comments on this website? Please give feedback.