There are always several ways to reach your goal. The shortest route is often the most efficient.
This also applies to approaches when optimizing queries.
In my case, I have extended the gallery snippet to display images in 3 different ways: as a masonry gallery, as a carousel or as a swiper gallery. Everything works perfectly. Nevertheless, I wonder if the query of the options in the template is elegantly solved or if there is a better way to do it. I am mainly concerned with the use of if/else queries.
snippets/blocks/gallery.php
<?php if ($block->galleryrepresentation()->value() === 'masonry') : ?>
<!-- etc. -->
<?php elseif ($block->galleryrepresentation()->value() === 'carousel') : ?>
<!-- etc. -->
<?php elseif ($block->galleryrepresentation()->value() === 'swiper') : ?>
<!-- etc. -->
<?php endif ?>
blueprints/blocks/gallery.yml
galleryrepresentation:
type: toggles
options:
- masonry
- carousel
- swiper
default: "masonry"
required: true
I guess you want different code per value, so the most elegant way would be to create snippets masonry.php
, gallery.php
etc. and then simply call
<?php snippet($block->galleryrepresentation()->value()) ?>
And pass the data you need to the snippet.
You can also prepend or append something to the snippet name if that makes more sense:
<?php snippet('gallery-block-type-' . $block->galleryrepresentation()->value()) ?>
Thanks for the quick reply. The code for the individual galleries is very extensive (OK, I admit it’s only 120 lines of code for all 3 galleries…), but is not used anywhere else on the website. It is therefore not necessary to outsource the code. I would even have 3 more files.
I am only concerned with the if/else queries, whether these have been solved well. Also, regarding possible sources of error if a value has not been set. Since you have not addressed this at all, my solution already appears to be optimal.
Even more reason to move them to a snippet to keep the block snippet clean. Snippets are not just about reuse, they are also about code cleanliness and avoiding unnecessary nested if statements.
But hey, up to you.