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