7

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

Something like:

$file = basename($path, ".php");
4
  • 2
    There is no such function - but you can easily just use a custom filter or function for that. See stackoverflow.com/questions/8180585/use-php-function-in-twig Commented Sep 15, 2015 at 15:16
  • 4
    Do you have an usecase where you want to use this? Seems something the controller should manage. Commented Sep 15, 2015 at 15:30
  • For sure, move your logic outside templates. Wondering how you get file instance in Twig. Commented Sep 15, 2015 at 16:42
  • Ok resolved, Thanks Alexander Kludt Commented Sep 21, 2015 at 10:32

3 Answers 3

7

if path equals /path/to/file.php, then

{{ path|split('/')|last|replace({'.php':''}) }}

will output file

Sign up to request clarification or add additional context in comments.

Comments

6

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
}) }}

Comments

5

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 }}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.