Hi
We're just building our first SilverStripe site and like most other sites we build at some point there is a requirement to incorporate a background image or content image dependent on the current page - i.e. if we're on page 6 show 6.jpg.
We have written a very short and simple function which will look to check if an image for the current page exists and show this if available. If an image is not found it will next look for a parent page and finally just pull a default image. It's then called in the template with a simple block of code.
In Page.php:
function SmartImage($folder, $filetype) {
$filename = 'assets/' . $folder . '/' . $this->ID . '.' . $filetype;
$parent_filename = 'assets/' . $folder . '/' . $parent->ID . '.' . $filetype;
if (Director::fileExists($filename)) {
$smartimagepath = $filename;
} elseif (Director::fileExists($parent_filename)) {
$smartimagepath = $parent_filename;
// to do - get top level id
} else {
$smartimagepath = '/assets/' . $folder . '/default.' . $filetype;
}
$data = array(
'SmartImagePath' => $smartimagepath
);
return $this->customise($data);
}
In Page.ss:
<% control SmartImage(sidebar,jpg) %>
<img src="$SmartImagePath" alt="" class="sidebar-img" />
<% end_control %>
Not sure if this is the best way to achieve this task in SilverStripe but it works for us. However I have a question I hope somebody can answer to further augment the code?
At the moment the function checks for an image based on the current page id, then the parent page id and then a default. It would be ideal if we could also check for an image matching the ID of the top level parent of the current page - i.e. the section page.
Does anybody have a suggestion on where we can retrieve this ID from?
Thanks
Simon