Timber wordpress - include with varriables

26 Views Asked by At

I have a hero-block.twig, which has the hero variable is set to fields.hero

{% set hero = fields.hero %}

{% for item in hero %}
 {{item.title}}
{% endfor %}

I want to include the hero-block.twig to other twig field, with the hero is replaced with post.meta('hero'), but the hero doesn't return any value. Am I making a mistake somewhere?

{% include "block/hero-block.twig" with { hero : post.meta('hero') }  %}
1

There are 1 best solutions below

0
Gchtr On

When you set hero in hero-block.twig, you currently always set it to fields.hero. You should add the logic so that hero can be overwritten.

{% set hero = hero ?? fields.hero %}

By using the null coalescing operator, you can check whether hero is passed in an include and use the passed hero value, or fall back to fields.hero.

If you only use the variable once, you can also directly us that in the for loop.

{% for item in hero ?? fields.hero %}
    {{ item.title }}
{% endfor %}