LoginSignup
4
8

More than 3 years have passed since last update.

EC-CUBE4 全ページで使える twig 変数を定義する方法

Last updated at Posted at 2019-09-13

値を静的に設定する方法

eccube_config に値を追加します。

source/app/config/eccube/packages/prod/eccube.yaml
parameters:
  env(VAR_TEST): 'DEFAULT VAR'
  var_test: '%env(VAR_TEST)%'
.env
VAR_TEST="TEST"

同様に source/app/config/eccube/packages/dev/eccube.yaml にも定義します。

なお source/app/config/eccube/packages/eccube.yaml は、バージョンアップなどで書き換わることがあるかもしれないので、手を加えないようにしています。

値を動的に設定する方法

例えば、カートに入っている情報を元に、送料無料条件を満たしているかを計算して
ページのヘッダーなどに、その状態を表示するときなどに使えそうです。

source/app/Customize/Event.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('var_test', 'TEST');
    }
}

なお、 KernelEvents::CONTROLLER_ARGUMENTS を Subscribe して以下のような
関数にコールバックする方法がありますが、お問い合わせフォームの確認画面のように
リクエストの途中でテンプレートが差し代わるような場合に、差し代わった方のテンプレートでは
変数が設定されていない状態となっていました。

source/app/Customize/Event.php
    /**
     * @param FilterControllerEvent $event
     */
    public function onKernelController(FilterControllerEvent $event)
    {
        if ($event->getRequest()->attributes->has('_template')) {
            $template = $event->getRequest()->attributes->get('_template');
            $this->eventDispatcher->addListener($template->getTemplate(), function (TemplateEvent $templateEvent) {
                $templateEvent->setParameter('var_test', 'TEST');
            });
        }
    }
4
8
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
8