问题
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!
回答1:
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 } %}
回答2:
You can use |default twig filter to determine a default value to a variable if the value is undefined or empty :
htmlLocale|default('en')
You can also check if the variable is empty and/or defined :
{% if htmlLocale is not empty and htmlLocale is defined %}
{% 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 %}
来源:https://stackoverflow.com/questions/38737639/twig-check-for-partial-existence-before-include