Home Top Ad

PHP basename Twig equivalent

Share:

 


Is there an equivalent function to PHP basename() in Twig ?

Something like:

$file = basename($path, ".php");

With Twig we can find the string after the last dot (.) and remove it from the string in order to get the filename (but it won't work if there is multiple dots).

{% set string = "file.php" %}
{{ string|replace({ ('.' ~ string|split('.')|last): '' }) }}
{# display "file" #}
{% set string = "file.html.twig" %}
{{ string|replace({ ('.' ~ string|split('.')|last): '' }) }}
{# display "file.html" and not "file" #}

Explanation:

{{ string|replace({     # declare an array for string replacement
    (                   # open the group (required by Twig to avoid concatenation with ":")
        '.'
        ~               # concatenate 
        string
            |split('.') # split string with the "." character, return an array
            |last       # get the last item in the array (the file extension)
    )                   # close the group
    : ''                # replace with "" = remove
}) }}


Aucun commentaire