Knowledge Base

Output Caption If Image Selected

Last Modified:
28 Jan 2025
User Level:
Power User
Complexity:
Beginner Friendly
Add some logic to your layouts to ensure that Image Captions only get output if an Image is selected

Conditional field rendering is a crucial technique that helps maintain clean, logical pages by controlling when specific content elements appear based on certain conditions being met. 

This approach prevents awkward gaps or orphaned labels in your pages that might occur when some content elements are empty or unused. For instance, displaying an “Image caption” only when an “Image” is present ensures your content remains coherent and professional-looking, avoiding situations where a standalone caption might appear without its corresponding image.

From Terminalfour 8.4.0 it’s possible to use the Conditional Elements feature to show or hide elements from your Content Editors based on some conditions, but you can also implement these conditional checks within your Content Layouts for full control of your content. Implementing these conditional checks not only improves the visual presentation of your content but also reduces potential confusion for your site visitors who might otherwise encounter contextless information. 

Conditionally outputting caption

In this example guide we’ll work with a very simple example of an Event content type with the following elements:

Name Type Size Required
Event Title Plain Text 150 Yes
Event Description HTML 10000 Yes
Event Image Media 80 No
Event Image Caption Plain Text 240 No

Notice that the Event Image element is not required. This means that a Content Editor could theoretically add an “Event Image Caption” but forget to add the image itself. 
In this situation we want to prevent the Caption being output.

But the Event Image Caption is also not required. So we only want that to be output if it is present as well.

We can do that with the following Handlebars code:

{{#ifSet element="Event Image"}}
  {{{publish element="Event Image"}}}
  {{#ifSet element="Event Image Caption"}}
    <div class="event-image-caption">
      {{publish element="Event Image Caption"}}
    </div>
  {{/ifSet}}
{{/ifSet}}

What this does

This code will first check that the user has selected an image in the “Event Image” element.
If they have, we’ll output that image. Before, we close out the ifSet though, we’ll do a check of the “Event Image Caption” element to see if the user added anything there. This second check is only run if the previous check for the “Event Image” was successful.

Finally, we’ll output the “Event Image Caption” in a div with a class so it can be styled appropriately.

Back to top