1
A
回答
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 }}
相關問題
- 1. Twig(symfony 2.0)中是否有include_partial等價物?
- 2. php的Javascript等價物move_uploaded_file
- 3. PHP的等價物str_word_count?
- 4. PHP islass的Scala等價物()
- 5. PHP的mysql等價物mysql_real_escape_string()
- 6. PHP的等價物Mcrypt
- 7. Python的等價物@
- 8. 什麼是PHP var_dump的.NET等價物?
- 9. PHP-CLI中的$ _ENV ['APACHE_RUN_USER']等價物
- 10. Python的等價物的PHP的虛擬()
- 11. MySQL的UNIX_TIMESTAMP()的PHP等價物?
- 12. 什麼是PHP的preg_quote的等價物?
- 13. 什麼是perl中$ _的php等價物?
- 14. 尋找getElementById和innerHTML的PHP等價物
- 15. PHP父::對象的等價物
- 16. PHP的ArrayObject是否有in_array等價物?
- 17. 什麼是PHP $ _ENV的Ruby等價物?
- 18. Python的等價物的php包
- 19. PHP的等價物.hasNext()和.hasNextLine()?
- 20. PHP的標題等價物包括
- 21. 在PHP中的quadraticCurveTo的等價物
- 22. python裝飾器的PHP等價物?
- 23. 什麼是PHP flush()的Java等價物?
- 24. Ruby的等價物的php史努比
- 25. PHP的get_file_contents()的Perl等價物?
- 26. PHP中的ASP.NET HttpModules的等價物
- 27. 在php中有什麼等價物?
- 28. Python的等價物PHP $ this - > {$ var}
- 29. iOS等價物onRestart()
- 30. Python等價物repr()?
沒有這樣的功能 - 但您可以輕鬆使用自定義過濾器或功能。請參閱http://stackoverflow.com/questions/8180585/use-php-function-in-twig –
你有使用這個用例嗎?似乎控制器應該管理的東西。 – Rvanlaak
當然,將您的邏輯移到模板之外。想知道如何在Twig中獲得文件實例。 – malcolm