How do I find the closest parent entry with an Assets field filled in? I have a structure that goes up to 4 levels deep. Each page has a field for a 'hero' image. If a child page does not have this field filled out I would like to traverse up the structure and find the closest parent entry with this field set. Basically some 'sections' would have a default hero image added to the top level parent while others may have a specific image for each child page.
You can get your entry's parent entry with getParent(). Use this entry method in a conditional, if your entry has no hero image set.

You can nest the code to climb up all of your structure's levels:

{# Check if entry has hero image #}
{% if entry.hero.first() %}
    {{ entry.hero.first().url }}
{% else %}

    {# Check the parent entry #}
    {% if entry.getParent().hero.first() %}
        {{ entry.getParent().hero.first().url }}
    {% else %}

        {# Check the entry 2 levels above #}
        {% if entry.getParent().getParent().hero.first() %}
            {{ entry.getParent().getParent().hero.first().url }}
        {% else %}

            {# ... Oh no, we're not finished yet :( #}

        {% endif %}

    {% endif %}

{% endif %}


Yes, that's not good code. That's why I recommend to use the same technique in a macro, that you can call recursively:

{% macro showHero(thisRecursionEntryModel) %}

    {% import _self as self %}

    {# Check if entry has hero image #}
    {% if thisRecursionEntryModel.hero.first() %}
        {{ thisRecursionEntryModel.hero.first().url }}
    {% else %}

        {# Check the entry's ancestors recursively #}
        {% if thisRecursionEntryModel.getParent() %}
            {{ self.showHero(thisRecursionEntryModel.getParent()) }}
        {% endif %}

    {% endif %}

{% endmacro %}

{% import _self as self %}
{{ self.showHero(entry) }}


You can also import the macro from a file, if you want to use it in more than one template file or just like your code to be modular:

{% import '_includes/macros.html' as macros %}
{{ macros.showHero(entry) }}