2015-09-15 87 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 }}