Twig Check for partial existence before include

ε祈祈猫儿з 提交于 2020-02-04 05:39:39

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!