3
3

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 3 years have passed since last update.

EC-CUBE4 テンプレートイベントでテンプレートに変数をセットする

Last updated at Posted at 2021-01-27

はじめに

カスタマイズ領域で進める場合、デザインテンプレートは簡単に切り替えられますが、テンプレートにセットする情報は、コントローラーイベントの EccubeEvents::FRONT_PRODUCT_DETAIL_INITIALIZE などをフックしても、テンプレートにデータを渡すことはできません。

そんな時は、対象のTwigテンプレートのパスでイベントを監視して、任意のデータをテンプレートに設定できます。

このようにすることで、デフォルトのコントローラーはそのままにしてカスタマイズが可能です。

イベントリスナーを用意する

<?php

declare(strict_types=1);

namespace Customize\EventListener;

use Eccube\Event\TemplateEvent;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;

class ProductDetailTwigEventListener implements EventSubscriberInterface
{
    public static function getSubscribedEvents(): array
    {
        return [
            'Product/detail.twig' => 'handle'
        ];
    }

    public function handle(TemplateEvent $event): void
    {
        $product = $event->getParameter('Product');
        if ($product === null) {
            return;
        }

        // do somithing
        $event->setParameter('test', 'TEST');
    }

}

テンプレートで出力する

app/template/your_template_code/Product/detail.twig
{{ test }}
3
3
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
3
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?