编辑:2016年12月3日
我发现了一些关于从twig调用php函数的帖子,表明应该支持它,但是它似乎不起作用。
{{ ucwords( item|replace({'_':' '}) ) }}
结果为:l
Slim Application Error
The application could not run because of the following error:
Details
Type: Twig_Error_Syntax Message: The function "ucwords" does not exist in "home.twig" at line 101
File: /usr/share/dev89/html/vhosts/local/libs/vendor/twig/twig/lib/Twig/ExpressionParser.php Line: 572
最佳答案
更新:Twig 2.x附带了 capitalize
过滤器,该过滤器正是这样做的。
在Twig中并不是所有的PHP函数都可用。只有少数Twig filters和functions的名称与PHP中的等效名称相同。
但是您可以轻松地为ucwords
创建自己的Twig extension –过滤器以及函数:
<?php
namespace Acme\TestBundle\Twig;
class UcWordsExtension extends \Twig_Extension
{
public function getFunctions()
{
return [
new \Twig_SimpleFunction('ucwords', 'ucwords')
];
}
public function getFilters()
{
return [
new \Twig_SimpleFilter('ucwords', 'ucwords')
];
}
public function getName()
{
return 'ext.ucwords';
}
}
Twig_SimpleFunction
/Twig_SimpleFilter
的第一个参数是Twig中函数/过滤器的名称。第二个参数是PHP可调用的。由于ucfirst
函数已经存在,因此足以将其名称作为字符串传递。在Twig中测试:
{{ "test foobar"|ucwords }} {# filter #} <br>
{{ ucwords("test foobar") }} {# function #}
返回值:Test Foobar
Test Foobar
关于twig - 如何在 Twig 上调用ucwords?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31145361/