Skip to content

Instantly share code, notes, and snippets.

@laras126
Last active March 6, 2016 17:40
Show Gist options
  • Save laras126/9681a4a633b428b7ad19 to your computer and use it in GitHub Desktop.
Save laras126/9681a4a633b428b7ad19 to your computer and use it in GitHub Desktop.
Conditional header display in Twig and ACF
{#
Use case:
You want to choose between a gallery vs. image display for the header of a page.
Notes about this code:
- It can be adapted to non-header parts of the site.
- It is not stand-alone, and would either be included in another Twig template (e.g. page.twig), or part of the template itself.
- The file is called header-page.twig so as not to conflict with custom page template naming conventions.
Assumes ACF fields for the following:
- a radio button field called type_of_header with options Gallery and Image
- a gallery field called header_gallery that is displayed if the above radio value is Gallery
- an image field called header_image that is displayed if the above radio value is Image
#}
{# If the field called type_of_header is equal to "Gallery", do the following: #}
{% if post.type_of_header == 'Gallery' %}
{# Since a Gallery field returns an array of attachment IDs, we need to loop through them. #}
{% for id in post.header_gallery %}
{# Retrieve the TimberImage object from the ID returned in the gallery array. Create a variable to store that object so we don't have to keep writing TimberImage(id). This is analogous to creating variables to store jQuery objects. #}
{% set img = TimberImage(id) %}
<div class="gallery-image">
{# Get the title of the image by calling the "title" value from the TimberImage object. #}
<h5>{{img.title}}</h5>
{# Get the image's path, called src (sometimes this is called URL in ACF.) Then add an alt tag with the image's title. #}
<img src="{{img.src|resize(800)}}" alt="{{img.title}}">
</div>
{# End the loop for the gallery array #}
{% endfor %}
{# Our next condition is for the header type of image. This is an image field, and we treat it similarly except it returns only one ID instead of an array like the gallery. We can test this using dump() #}
{% elseif post.type_of_header == 'Image' %}
{# Get the TimberImage object from the ID returned from the post.header_image custom field, and make it a but shorter for ease of use. #}
{% set hdr_img = TimberImage(post.header_image) %}
{# Get the source and title data from the TimberImage object above. We are storing the object in a variable to help shorten up our code and make it more readable. #}
<img src="{{hdr_img.src}}" alt="{{hdr_img.title}}">
{# End the conditional. #}
{% endif %}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment