I am developing a plugin in shopware 6 and I want add code to the footer when the page loads. I've tried several things but it doesn't work for me. How should I continue?
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Shopware\Storefront\Event\StorefrontRenderEvent;
class MyPluginFrontendSubscriber implements EventSubscriberInterface
{
private $twig;
public function __construct(\Twig\Environment $twig)
{
$this->twig = $twig;
}
public static function getSubscribedEvents(): array
{
return [
StorefrontRenderEvent::class => 'onRenderFooter'
];
}
public function onRenderFooter(StorefrontRenderEvent $event)
{
$template = '@MyPlugin/storefront/layout/base/customjs.html.twig';
//I dont know to do here
}
}
public function onRenderFooter(StorefrontRenderEvent $event)
{
$this->twig->addGlobal('shopware', array_merge(
$this->twig->getGlobals()['shopware'],
['footer' => $this->twig->render('@MyPlugin/storefront/layout/base/customjs.html.twig')]
));
}
Dont work
You can extend a template by matching the path of the template and using sw_extends
.
<PluginDir>/src/Resources/views/storefront/base.html.twig
{% sw_extends '@Storefront/storefront/base.html.twig' %}
{% block base_body_script %}
{{ parent() }}
<script>...</script>
{% endblock %}
If it's just about adding custom javascript also consider this way to go about it.
For adding variables to be used in the template programmatically, see this part of the documentation.