簡體   English   中英

如何向 Twig (symfony3) 添加自定義函數?

[英]How can i add custom function to twig (symfony3)?

我將此代碼添加到 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:第 24 行的“gecis/gecis.html.twig”中的“未知的“gecis”函數。” 在 C:\\wamp64\\www\\deneme\\vendor\\twig\\twig\\lib\\Twig\\ExpressionParser.php line 573 {"exception":"[object] (Twig_Error_Syntax(code: 0): Unknown \\"gecis\\" function in \\"gecis/gecis.html.twig\\" 在第 24 行。在 C:\\wamp64\\www\\deneme\\vendor\\twig\\twig\\lib\\Twig\\ExpressionParser.php:573)"}

我的錯誤在哪里?

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.

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM