Inject variables in all templates

Create a new TwigGlobalSubscriber.php file in src/Twig

<?php

namespace App\Twig;

use Metabolism\WordpressBundle\Repository\PostRepository;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpKernel\KernelEvents;
use Twig\Environment;

class TwigGlobalSubscriber implements EventSubscriberInterface {

	/**
	 * @var Environment
	 */
	private $twig;
	private $postRepository;

	public function __construct( Environment $twig, PostRepository $postRepository) {

		$this->twig = $twig;
		$this->postRepository = $postRepository;
	}

	public function injectGlobalVariables() {

		$guides = $this->postRepository->findBy(['post_type'=>'guide'], null, -1);
		$this->twig->addGlobal('guides', $guides);
	}

	public static function getSubscribedEvents() {

		return [ KernelEvents::CONTROLLER =>  'injectGlobalVariables' ];
	}

	public function onKernelRequest()
	{
	}
}

Edit config/services.yaml

    App\Twig\TwigGlobalSubscriber:
        tags:
            - { name: kernel.event_listener, event: kernel.request }

Use the variable directly in your twig template

{% for guide in guides %}
  {{ guide.title }}
{% endfor %}

Last updated