0

How can I use f:if to see if an image exists on the server before trying to render it?

I have tried the following without success:

<f:if condition="fileadmin/bilder/Header/{data.title}.jpg">
    <f:then>
        <f:variable name="imageUri" value="fileadmin/bilder/Header/{data.title}.jpg" />
    </f:then>
    <f:else>
        <f:variable name="imageUri" value="fileadmin/bilder/Header/default.jpg" />
    </f:else>
</f:if>

{data.title} works correkt. The Problem is that my condition is wrong. It never goes to the else. Probably my condition is interpret as a string und not as an source.

Description here doesn´t help because my Image is on the server. Render image in fluid template if it exists?

Melanie
  • 1
  • 1
  • 1
    What is the purpose of your check? I guess you look for a header image on a page? Why not putting the image into the page properties and let TYPO3 fetch it easily with TypoScript? – Thomas Löffler Oct 21 '19 at 14:13
  • My first thought was to put the image into the page properties, but I have two possible pictures, one for the header and one for the menu. And it is possible that it exists only one and I cannot differ which picture it is. – Melanie Oct 23 '19 at 07:13

1 Answers1

1

First of all, why would you have a hardcoded path to a file in fileadmin in a template? That's very uncommon, most of the time you have some kind of relation through TYPO3 (e.g. through the media field in the pages table or something like that).

If this is still something you need, you'd have to write a FileExistsViewHelper that checks if the file exists before using it. Here's the documentation on how to write a custom view helper: https://docs.typo3.org/m/typo3/book-extbasefluid/master/en-us/8-Fluid/8-developing-a-custom-viewhelper.html You'd need to register your filename as an argument with registerArgument and then prepend the path to the TYPO3 installation (to make it an absolute path) and check for this file with file_exists. Extend from \TYPO3Fluid\Fluid\Core\ViewHelper\AbstractConditionViewHelper and implement the verdict method.

Your template above just creates a string (as you already guessed).

Wolfgang
  • 593
  • 3
  • 8
  • If you're using ext:vhs there is a Viewhelper you can use https://fluidtypo3.org/viewhelpers/vhs/master/Media/ExistsViewHelper.html – paskl Oct 21 '19 at 12:43