BlueDogRanch
BlueDogRanch

Reputation: 575

Using an ACF gallery with Timber/Twig

I'm using Timber (the WordPress plugin implementation of Twig) and the Advanced Custom Fields plugin gallery field. I have a working gallery under a custom post type, so ACF and Timber are working elswhere in the site, but not for a standard page. When I try to add a gallery to a page, all I end up with is empty markup for the img src tag.

I have this in page.php in the template folder:

$context = Timber::get_context();
$page = new TimberPost();

$context['page'] = $page;

if ($photos = $page->get_field('photos')) {
    $context['photos'] = $photos;
}

I have this in default.twig in the templates/page/ folder in the theme (html removed for simplicity):

{% if page.photos %}

{% for p in page.photos %}

<img src="{{ p.sizes.gallery|relative }}" alt="{{ p.alt }}" /> 

{{ p.caption }}

{% endfor %} 

{% endif %}

This results in the page source <img src="" alt="">.

If I use {{ dump(photos) }} inside the for p in page.photos statement, it dumps the array of images I have entered in the Gallery field on the backend. So the image array exists and it being output. The relative extension runs for all post types; removing it makes no difference here.

So why is the p.sizes.gallery|relative function not outputting each image's url and caption?

Upvotes: 2

Views: 1874

Answers (2)

Sonia Verma
Sonia Verma

Reputation: 81

I have tested everything is working fine. Only thing which is incorrect is how the images are fetching in image tag. That's the reason for empty source and alt tag <img src="" alt="">.

Image tag supposed to be like this:

<img src="{{ Image(p).src }}" alt="{{ Image(p).alt }}"/>

For more information use Timber official website for image related syntax. For Advanced custom field gallery syntax use this reference: https://timber.github.io/docs/guides/acf-cookbook/#gallery-field

Upvotes: 0

Owi
Owi

Reputation: 498

You append the data to the $context['photos'] so I believe you should change your code to check for if photos and iterate as for p in photos

Upvotes: 1

Related Questions