我将此代码添加到service.yml
//app/config/services.yml
services:
TwigEkler:
class: MainBundle\Twig\TwigEkler
tags:
- { name: TwigEkler }
并创建了这个文件
//src/MainBundle/Twig/TwigEkler.php
<?
namespace MainBundle\Twig;
class TwigEkler extends \Twig_Extension
{
public function getFunctions()
{
return array(
new \Twig_SimpleFunction('gecis', array($this, 'gecisFunction')),
);
}
public function gecisFunction($param)
{
if ($param == '4') {
return 'FAT';
} else {
return '';
}
}
public function getName()
{
return 'TwigEkler';
}
}?>
并在树枝中使用它
{{ gecis(level) }}
但我收到此错误
request.CRITICAL:未捕获的PHP异常Twig_Error_Syntax:&#34;未知 &#34; GECIS&#34;功能在&#34; gecis / gecis.html.twig&#34;在第24行。&#34;在 C:\ wamp64 \ www \ deneme \ vendor \ twig \ twig \ lib \ Twig \ ExpressionParser.php line 573 {&#34;例外&#34;:&#34; [对象](Twig_Error_Syntax(代码:0):未知 \&#34; GECIS \&#34;功能在\&#34; gecis / gecis.html.twig \&#34;在第24行 C:\ wamp64 \ WWW \ deneme \厂商\树枝\树枝\ lib中\嫩枝\ ExpressionParser.php:573)&#34;}
我的错误在哪里?
答案 0 :(得分:0)
you need to follow
create a directory in your AppBundle " Extensions "
and create a file " TwigExtensions.php "
In that file you need to define:
namespace AppBundle\Extensions;
use Symfony\Bridge\Doctrine\RegistryInterface;
use AppBundle\Helper\CommonHelper;
class TwigExtensions extends \Twig_Extension
{
public function __construct(RegistryInterface $doctrine){
$this->doctrine = $doctrine;
}
}
Use
public function getFunctions(){
//Define your function that you
}
}
Than create the function that you have define in " getFunctions".
Now you can use that function on twig.