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.

Archive /

Our old forums are still available as a read-only archive.

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

Conditionally inserting image


Go to End


4 Posts   1751 Views

Avatar
gakenny

Community Member, 153 Posts

17 October 2007 at 10:12pm

Hello,

I would like to conditionally insert an image into Page.ss based on the value of $URLSegment and the presence of the image file:

First problem:
I am trying to generate the HTML to display the image and I have inserted the following code into Page.ss.

<img class="center" src="assets/images/$URLSegment.jpg" alt="$Title" width="520" />

However, $URLSegment and .jpg is replaced with blank, ie. src=""assets/images/"

Second problem:
How do I detect the existence of this file in Page.ss so as to only insert the relevant HTML if the file exists?

Cheers,

Gary

Avatar
gakenny

Community Member, 153 Posts

19 October 2007 at 9:24pm

Hello,

To resolve this issue I inserted $URLSegment inside curly brackets ('{$URLSegment}').

I hope this helps.

Cheers,

Gary

Avatar
Sean

Forum Moderator, 922 Posts

22 October 2007 at 9:16pm

Edited: 22/10/2007 9:17pm

Optionally, you could make a new function called ImagePath() on your class and use $ImagePath in the template, instead. This would automatically find the relative path, like assets/images/$URLSegment, so you just need to insert <img src="$ImagePath" alt="My image" /> - this avoids the problem of having curly braces in your nice templates. :-)

function ImagePath() {
return 'assets/images/' . $this->URLSegment . '.jpg';
}

<% if ImagePath %>
<img src="$ImagePath" alt="My image" />
<% end_if %>

Cheers,
Sean

Avatar
gakenny

Community Member, 153 Posts

23 October 2007 at 10:13am

Thanks Sean - I might just try that.

Initially, I wasn't sure if I could pass a variable back from a function. I have been plugging away at the templating engine at the weekend and have made some breakthroughs - thanks to your support!

Many thanks,

Gary