Timber is a plugin to allow separation between PHP and HTML files. Click here for introduction.
Timber works well with ACF but Flexible Content requires a bit of different approach to integrate. We will take a look at how to do it here.
Let’s say we have a flexible content field named layouts
that has 3 layouts: Free Content, Gallery, and Testimonials like pictured below:
In your views folder, create a new folder called /builders
(you’re free to use any name) and create new Twig files with exact same name as the layout’s:
...
views/
├── layouts/
│ ├── free_content.twig
│ ├── testimonials.twig
│ ├── gallery.twig
├── ...
...
In your Page view, add a loop for the Flexible Content field:
{% for layout in post.get_field("layouts") %}
{% include "layouts/" ~ layout.acf_fc_layout ~ ".twig" %}
{% endfor %}
Inside the layout file, you still have access to the layout
variable given by the loop:
<section class="free-content-layout">
<h2>{{ layout.title }}</h2>
{{ layout.content }}
</section>
<section class="gallery-layout">
<h2>{{ layout.title }}</h2>
<div class="gallery-items">
{% for i in layout.images %}
<figure>
<img src="{{ i.sizes.thumbnail }} alt="{{ i.alt }}">
</figure>
{% endfor %}
</div>
</section>
Simple enough right? I believe you can take it from here and write the code for other layouts.
Conclusion
ACF and Timber works really well with each other. All fields can be accessed by post.get_field()
function, but for subfield like the one in Repeater and Flexible Content, you can access it directly with dot array notation.
If you want to know what a variable holds, simply dump it like this:
{{ dump( var_name ) }}
It’s the same as using var_dump()
in PHP. That is how I know that the layout name is stored inside acf_fc_layout
.
Please leave a comment if you have any question regarding Flexible Content in Timber 🙂
Hi!
Thanks for this guide.
Just wanted to point out that you've called your flexible content field "Builders" but called it "layouts" in the page template. 🙂 So you can't access the field with the incorrect name!
Hi Stefanie, Thanks for the correction! Appreciate it
Hi ! Great technique. A way to improve it and avoid breaking errors when the corresponding template doesn't exist for the layout is to add "ignore missing" like this :
{% include "layouts/" ~ layout.acf_fc_layout ~ ".twig" ignore missing %}
Timber doc as reference: https://timber.github.io/docs/guides/cookbook-twig/#dynamic-includes
Nice tips, didn't know Timber has this option. Thanks