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
}) }}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With