Im new to Kirby/PHP and loving it, but have hit a road block so any help would be greatly appreciated!
I am looking to create a simple gallery page where the client can drag an image from the page files into an image field and also write an image caption.
I have been able to create the blueprint using ‘Structure Field Content’ which outputs correctly in the panel, but the issue is fetching the image in the template. The caption is appearing and the tag is displaying in the browser but the img/path is just displaying the ‘www.website/page’ so no image is loading.
One question before I can provide an answer: what’s $pic->title() ?
Is it a field in your image meta? Is it the name of the image file? I don’t see it in your blueprint.
At first, I think, it should be <?php echo $pic->image()->url() ?> instead of <?php echo $pic->image->url() ?>.
But then you would try to get some field named image, which does not exist, because your image name is saved in gallery_image.
But to use the url() method, you must have an image object first, wich you can get via the image() function like this:
$img = $page->image($pic->gallery_image());
With this image object, you can generate thumbs, get the url and any other field saved in the image meta file. The caption field will remain the same as it is now.
Alt text and caption can be a bit redundant depending on how you use them. I think the alt text is meant to be very short and descriptive while a caption can provide additional information. There are lots of interesting reads online (I just spent 25 minutes reading through a few)
Here’s the full code for you. I’m using an if statement to verify that the image exists, to avoid throwing errors.
If your images are all in the structure field, you just need to loop through them like in the code above, no need for a second foreach loop. But if you want to have different classes for each field, you would have to define these classes somewhere, e.g. in a field within the structure field or in the image meta file.
Ok so I have removed $pic->gallery_image_2() and looping with foreach. But this returns the same image in every div. How can I display different image in each div?
So your structure field contains only one image, there is not a lot you can loop through in that case You would have to add more structure field entries.
When I add another image and caption in the panel (see below) it repeats the first image in each seperate ‘figure’ then repeats the whole section again for the second image repeating the image in every ‘figure’. This is what is confusing me?!
The problem is that you repeat the same figure/image again and again. The whole purpose of using a foreach loop is that the loop fetches all elements and repeats the same action for each element.
So your code should just consist of this bit of code and nothing else: