Showing a default image with Timber on search results

I’m just getting started with Timber and I have a doubt about showing images on search results. I’m trying to handle the search results of posts that have no featured images in a slightly different way.

I currently get the post results on the search.php from:

$templates = array(‘search.twig’, ‘archive.twig’, ‘index.twig’);
$context = Timber::get_context();

$context[‘title’] = ‘Search results for “‘. get_search_query() . ‘”‘;
$context[‘posts’] = Timber::get_posts();
$context[‘posts’] = Timber::get_posts();

Then on my search.twig I get all the posts content with

{% for post in posts %}
{% include [‘tease-‘~post.post_type~’.twig’, ‘tease.twig’] %}
{% endfor %}

and on tease.twig I show the post thumbnail with

<div class=”tease-image”><img src=”{{post.thumbnail.src|resize(300, 300)}}” alt=””></div>

All clear and simple so far!
Then I can do a simple

{% if post.thumbnail.src %}

To show something else if a post doesn’t have a featured image. Simple.

Now, I want to create an array of other ‘fallback images’ that I can load and randomly show on the tease.twig if the featured image is empty.

I can easily do this with PHP

if ( has_post_thumbnail() ) {
the_post_thumbnail();
} else { echo ‘<img src=”‘.bloginfo(‘template_directory’).’/images/default-image.jpg” alt=”” />’;}

But how to I load these back into Timber to access them on the twig template?

Thanks a lot for any help.

Read more here:: Showing a default image with Timber on search results

Leave a Reply

Your email address will not be published. Required fields are marked *