Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Twig Check for partial existence before include

Tags:

twig

symfony

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!

like image 491
Alex Avatar asked Aug 03 '16 07:08

Alex


1 Answers

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 } %}
like image 196
DarkBee Avatar answered Nov 15 '22 11:11

DarkBee