Set a variable

Estimated reading: 1 minute

Many times having to write out nested variables can get lengthy, let alone be more error prone. You can assign temporary variables to make it easier:

{# employee CPT has a field called 'employee_image' which is a ACF field that is returned as an attachment ID #}
{% set headshot = TimberImage( tb.get_field( 'employee_image' ) ) %}

Which gets the ‘employee_image‘ field, turns it into a TimberImage object and stores it in a variable named ‘headshot‘. Now everytime we need something for that image, we can just query the ‘headshot‘ variable:

{# employee CPT has a field called 'employee_image' which is a ACF field that is returned as an attachment ID #}
{% set headshot = TimberImage( tb.get_field( 'employee_image' ) ) %}
<img src="{{ headshot.src }}" width="{{ headshot.width }}" height="{{ headshot.height}}" alt="{{ headshot.alt }}">

Why not headshot.thumbnail.src ?

You might be wondering why we’re accessing the src, width, height and alt property directly on the ‘headshot’ variable. Why do we not use headshot.thumbnail.src instead?

The reason is of course that when we set the variable, we set it to be the actual image itself. On a TimberPost object, the image is the post.thumbnail property, so we must target that to get the info we need.

Share this Doc

Set a variable

Or copy link

CONTENTS