Adding a class to an image depending on select-field option

I’d like to be able to assign classes to images via a selection field that I added to the images’ meta info.

My blueprint looks as follows:

files:
    sortable: true
    fields:
      caption:
        label: Image Position
        type: select
        options:
          center:       Center
          center-right: Center-Right
          center-left:  Center-Left
          bottom-right: Bottom-Right
          bottom-left:  Bottom-Left
          top-right:    Top-Right
          top-left:     Top-Left

Each of the options refers to a CSS class. In the backend this results in the following:

51

As of right now I’m simply pulling the images into the page like this (the images are put into a flickity-based slider):

<div class="main-carousel">

<?php foreach($project_cd_images->sortBy('sort', 'asc') as $project_cd_image): ?>

	<!-- Add each image to slider as bg-img -->
		<div class="carousel-cell--half">
			<div 	class="tbn-slider--bg-img tbn-slider--bg-img-regular"
						style="	background-image: 
										
										url(<?= $project_cd_image->url() ?>);

										background-position: center;">
			</div>
		</div>
	<!-- –––––––––––––––––––––––––––––––––– -->

<?php endforeach ?>

</div>

Everything is working out perfectly fine, the images in the backend are put into the slider as background-images of a respective <div>without any problems.

Now I would like to also be able to check the selection made in the “Image Position”-field (see above) before the image is placed in the slider and assign the <div> class depending on that selection. How do I check for the selected option in the field and assign the class?

Thanks in advance for any help.

<div class="main-carousel">

<?php foreach($project_cd_images->sortBy('sort', 'asc') as $project_cd_image): ?>
  <?php $imagePosition = $project_cd_image->caption(); ?>
	<!-- Add each image to slider as bg-img -->
		<div class="carousel-cell--half">
			<div 	class="tbn-slider--bg-img tbn-slider--bg-img-regular <?= $imagePosition ?>"
						style="	background-image: 
										
										url(<?= $project_cd_image->url() ?>);

										background-position: center;">
			</div>
		</div>
	<!-- –––––––––––––––––––––––––––––––––– -->

<?php endforeach ?>

</div>

Since your field is not required, you might want to add an if statement to check if the variable is empty and maybe assign a default class.

2 Likes