4
7

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

symfony twig拡張メモ

Last updated at Posted at 2016-11-17

symfony公式にはfilterしか書いてないのでよく使いそうな
function,filter,globalのtwig拡張のメモ。

###クラス例

namespace CommonBundle\Twig\Extension;

class CommonExtension extends \Twig_Extension implements \Twig_Extension_GlobalsInterface
{

    protected $container;

    public function __construct(ContainerInterface $container)
    {
        $this->container = $container;
    }

    public function getName()
    {
        return "common_extension";
    }

    /**
     * twigで使用するfilterを設定
     *
     * @return array
     */
    public function getFilters() {
        return [
            new \Twig_SimpleFilter('date'  ,[$this, 'dateFilter']),
           ];
    }


    /**
     * twigで使用するfunctionを設定
     *
     * @return array
     */
    public function getFunctions() {
        return [
            new \Twig_SimpleFunction('testFunction', [$this, 'testFunction']),
        ];
    }

    /**
     * twigで使用するglobal変数を設定
     *
     * @return array
     */
    public function getGlobals()
    {
       //twig内で使用したい変数とかを返り値に設定
        $user = "hogehoge";
        return [
            'user' => $user,
        ];
    }

    /**
     * @param  $dateTime
     * @return string
     */
    public function dateFilter($dateTime)
    {
        // 何か処理
        return $hoge;
    }

        /**
     * @param  hoge 
     * @return string
     */
    public function testFunction($hoge)
    {
        // 何か処理
        return $hoge;
    }
}

DI設定

####service.yml
サービスコンテナーを使う場合

    common.twig.extension:
        class: CommonBundle\Twig\Extension\CommonExtension
        arguments: ['@service_container' ]
        tags:
            - { name: twig.extension }

###twig側

####filter

{{ dateTime|date }}

####function

{{ testFunction("hogehoge") }}

getGlobalで指定した変数はtwig側でも使えるようになる

{{ user }}
hogehoge

と出るはず。

4
7
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
7

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?