PHP basename Twig 等价物

spi*_*oza 4 symfony twig

basename()Twig 中是否有与 PHP 等效的功能?

就像是:

$file = basename($path, ".php");
Run Code Online (Sandbox Code Playgroud)

A.L*_*A.L 5

使用 Twig,我们可以找到最后一个点 ( .)之后的字符串,并将其从字符串中删除以获得文件名(但如果有多个点,它将不起作用)。

{% 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" #}
Run Code Online (Sandbox Code Playgroud)

解释:

{{ 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
}) }}
Run Code Online (Sandbox Code Playgroud)


fyr*_*rye 5

默认情况下basename,Twig 中没有默认的过滤器样式,但是如果您需要使用自己的扩展默认的 Twig 过滤器或函数,您可以按照您的 Symfony 版本的说明书中的描述创建一个扩展。 http://symfony.com/doc/current/cookbook/templating/twig_extension.html

树枝延伸

// 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);
    }
}
Run Code Online (Sandbox Code Playgroud)

配置文件

# app/config/services.yml
services:
    app.twig_extension:
        class: AppBundle\Twig\TwigExtension
        public: false
        tags:
            - { name: twig.extension }
Run Code Online (Sandbox Code Playgroud)

树枝模板

{% set path = '/path/to/file.php' %}
{# outputs 'file.php' #}
{{ path|basename }}

{# outputs 'file' #}
{{ path|basename('.php') }}

{# outputs 'etc' #}
{{ '/etc/'|basename }}


{# outputs '.' #}
{{ '.'|basename }}

{# outputs '' #}
{{ '/'|basename }}
Run Code Online (Sandbox Code Playgroud)