Parameterize YAML data

Hi guys,

I’m using the code below to loop through events.

<?php
// get all events
$events = $page->events()->toStructure();

// loop through the collection of events:
foreach($events as $event): ?>

  <h1><?php echo $event->event_title()->html() ?></h1>
  <p><?php echo date('Y-m-d', strtotime($event->event_date())) ?></p>
  <p><?php echo $event->event_location()->html() ?></p>
  <?php if($image = $event->event_image()->toFile()) echo $image->html() ?>

<?php endforeach ?>

Works fine, so no problem there. However, I have to specify the image file in the YAML front matter. What I’d like to achieve is that I enter the event name in the YAML data (“Conference about X”) and that the foreach loop

  1. modifies “Conference about X” to “conference-about-x”;
  2. pulls an image file “conference-about-x.jpg” into the loop.

That would save me the time to enter all image paths into the YAML data and would allow for further standardization.

Thanks in advance :slight_smile:

You can use str::slug() to modify the title like this:

$imageName = str::slug($event->event_title());
if($image = $page->image($imageName)) {
  // do stuff
}

Thanks, I’ll look into that. Couldn’t get it to work on the first try but I’m fairly new to PHP…

Somewhat related question: all this is happening on an “Events” page. I have specified the image file name (“event_image: conference-about-x.jpg”). I’d like to place these images either in a subdirectory of the content folder, or - preferably - in “assets / images / events”.

When I change the YAML data to “event_image: images/conference-about-x.jpg” it doesn’t work anymore. Help on how to get this working is greatly appreciated :slight_smile:

Sorry, there was a typo above, which I corrected. Also, you would have to add the image extension somehow, provided that the images are in the events page, which I forgot. Here is a corrected version:

$imageName = str::slug($event->event_title());
if($image = $page->images()->findBy('name', $imageName)) {
  // do stuff
}

The easiest way would be to put the images in the events page, or in a subfolder thereof.

Assuming the images are in a subfolder like /events/event-images/:

$imageName = str::slug($event->event_title());
if($image = $page->children()->find('event-images')->images()->findBy('name', $imageName)) {
  // do stuff
}

Edit: Are you using the Panel? If so, I wouldn’t put them into assets, because that folder is not accessible via the Panel. It is also easier to work with images if they are located in the content folder.

1 Like