Is there an equivalent function to PHP basename()
in Twig ?
Something like:
$file = basename($path, ".php");
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
}) }}
By default there is no default basename
style of filter in Twig, but if you need to extend the default Twig filters or functions with your own, you can create an extension as described in the cookbook for your version of Symfony.
http://symfony.com/doc/current/cookbook/templating/twig_extension.html
Twig Extension
// src/AppBundle/Twig/TwigExtension.php
namespace AppBundle\Twig;
class TwigExtension extends \Twig_Extension
{
public function getName()
{
return 'twig_extension';
}
public function getFilters()
{
return [
new \Twig_SimpleFilter('basename', [$this, 'basenameFilter'])
];
}
/**
* @var string $value
* @return string
*/
public function basenameFilter($value, $suffix = '')
{
return basename($value, $suffix);
}
}
Config File
# app/config/services.yml
services:
app.twig_extension:
class: AppBundle\Twig\TwigExtension
public: false
tags:
- { name: twig.extension }
Twig Template
{% set path = '/path/to/file.php' %}
{# outputs 'file.php' #}
{{ path|basename }}
{# outputs 'file' #}
{{ path|basename('.php') }}
{# outputs 'etc' #}
{{ '/etc/'|basename }}
{# outputs '.' #}
{{ '.'|basename }}
{# outputs '' #}
{{ '/'|basename }}