Subscriber for all Storefront pages in Shopware 6

/

Recently I stumbled upon the problem that I needed some data inside the base.html.twig and since that view is used everywhere and I needed extra data from the database in there, I had to add a Subscriber to an event that is called on all pages. Here’s the code:

File Path: /custom/plugins/PLUGIN_NAME/src/Storefront/Subscriber/StorefrontSubscriber.php

<?php declare(strict_types = 1); namespace %NAMESPACE%\Storefront\Subscriber; use Shopware\Storefront\Event\StorefrontRenderEvent; use Symfony\Component\EventDispatcher\EventSubscriberInterface; class StorefrontSubscriber implements EventSubscriberInterface { public static function getSubscribedEvents(): array { return [ StorefrontRenderEvent::class => 'onStorefrontRender' ]; } public function onStorefrontRender(StorefrontRenderEvent $event) { $event->setParameter('%YOUR_VIEW_NAMESPACE%', 'SOME_DATA'); } }

Now anything you added to the view with $event->setParameter() is available in all views on all pages (on the Storefront).

File Path: /custom/plugins/PLUGIN_NAME/src/Resources/views/storefront/base.html.twig

{% sw_extends '@Storefront/storefront/base.html.twig' %} {% block base_body_script %} {{ parent() }} {{ %YOUR_VIEW_NAMESPACE%|json_encode }} {% endblock %}

Leave a Comment