Alex Alex - 4 months ago 10
Twig Question

Twig Check for partial existence before include

I am working on a fairly complex multi lingual site that will render different partials based on the html locale.

I have a partial structure that will use the locale appended to the file name to pick the right one. For example;

{% include '@BundleName/Layout/Text/_partial-name.' ~ htmlLocale ~ '.html.twig' with {'title' : resource.title } %}


Whilst this works, there is a risk if the locale selected has not (yet) had its partial created, this will throw an error. What i would like to do is check for the existence of the partial before trying to render it and fall back to a default if it does not yet exist.

{% if '@BundleName/Layout/Text/_partial-name.' ~ htmlLocale ~ '.html.twig' %}
{% include '@BundleName/Layout/Text/_partial-name.' ~ htmlLocale ~ '.html.twig' with {'title' : resource.title } %}
{% else %}
{% include '@BundleName/Layout/Text/_partial-name.html.twig' with {'title' : resource.title } %}
{% endif %}


Obviously that doesn't work, but that's the kind of thing i am after!

Answer

Rather than to test if the partial exists you can use ignore missing:

{% include 'partial.html' ignore missing %}

If you do wish to have a fallback when the file is missing you can pass an array to the include function. This will make the include render the first found template in the array

{% include  [
                ('@BundleName/Layout/Text/_partial-name.' ~ htmlLocale ~ '.html.twig'), 
                '@BundleName/Layout/Text/_partial-name.html.twig'
            ] with {'title' : resource.title } %}