Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP basename Twig equivalent

Tags:

twig

symfony

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

Something like:

$file = basename($path, ".php");
like image 993
spinoza Avatar asked Dec 10 '22 21:12

spinoza


1 Answers

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
}) }}
like image 185
A.L Avatar answered Dec 25 '22 00:12

A.L