【EC-CUBE4】全Twigで使用できる共通変数を設定する

めだま

EC-CUBE4にて、すべてのtwigファイルで共通使用できる変数を設定する

Event.php作成

  • app/Customize/Event.php
<?php

namespace Customize;

use Eccube\Request\Context;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpKernel\Event\GetResponseEvent;
use Symfony\Component\HttpKernel\KernelEvents;
use Twig\Environment;

class Event implements EventSubscriberInterface
{
    /** @var Context */
    protected $requestContext;

    /** @var Environment */
    protected $twig;

    /**
     * Event constructor.
     *
     * @param Context $requestContext
     * @param Environment $twig
     */
    public function __construct(
        Context $requestContext,
        Environment $twig
    )
    {
        $this->requestContext = $requestContext;
        $this->twig = $twig;
    }

    /**
     * @return array
     */
    public static function getSubscribedEvents()
    {
        return [
            KernelEvents::REQUEST => ['onKernelRequest', 100000000]
        ];
    }

    /**
     * @param GetResponseEvent $event
     */
    public function onKernelRequest(GetResponseEvent $event)
    {
        // 管理画面は除外
        if ($this->requestContext->isAdmin()) {
            return;
        }

        // ⭐️ ここで共通変数設定
        $this->twig->addGlobal('test', 'testだよ');
    }
}

Twigで表示してみる

  • お好みのtwigで
{{ test }}

\ 案件のご依頼・ご相談はこちらから /