2015-09-15 54 views
1

Twig中是否有与PHP basename()等价的函数?PHP basename Twig等价物

喜欢的东西:

$file = basename($path, ".php"); 
+1

没有这样的功能 - 但您可以轻松使用自定义过滤器或功能。请参阅http://stackoverflow.com/questions/8180585/use-php-function-in-twig –

+3

你有使用这个用例吗?似乎控制器应该管理的东西。 – Rvanlaak

+0

当然,将您的逻辑移到模板之外。想知道如何在Twig中获得文件实例。 – malcolm

回答

3

随着枝条,我们可以找到最后一个点(.)后的字符串,从字符串,以获得的文件名删除它(但如果它不会工作多个点)。

{% 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" #} 

说明:

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

默认情况下存在嫩枝过滤器没有默认basename的风格,但如果你需要用自己的扩展默认的枝条过滤器或功能,您可以创建一个扩展如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); 
    } 
} 

配置文件

# app/config/services.yml 
services: 
    app.twig_extension: 
     class: AppBundle\Twig\TwigExtension 
     public: false 
     tags: 
      - { name: twig.extension } 

嫩枝模板

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

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

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


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

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