Wordpress Bundle
  • What is Wordpress Bundle?
  • Getting started
    • Installation
    • Wordpress
    • Router
    • Cron job
    • Templates
  • Reference
    • Argument resolver
    • Controller
      • AdminAction
      • BlogController
      • FrontAction
      • WordpressAction
    • Entity
      • Block
      • Blog
      • Comment
      • File
      • Image
      • Menu
      • MenuItem
      • Post
      • Term
      • User
    • Repository
      • CommentRepository
      • PostRepository
      • TermRepository
      • UserRepository
    • Service
      • PaginationService
      • BreacrumbService
  • Guides
    • Server requirements
    • Install plugins
    • Use Multisite
    • Gutenberg
    • WP Steroids plugin
      • Image options
      • Maintenance
      • Admin pages removal
      • WYSIWYG Editor
      • Feature Support
      • Multi-site configuration
      • Constants definition
      • ACF configuration
      • Menu
      • Custom Post type
      • Advanced permalink settings
      • Custom Taxonomy
      • Templates
      • Page states
      • External table viewer
      • Roles
      • Optimisations
      • Security
      • Search
    • Twig Cookbook
    • Inject variables in all templates
    • Internationalization
    • Extending Wordpress Bundle
    • Error pages
    • Site health
  • Integrations
    • Advanced Custom Fields
      • Install ACF PRO
  • Extras
    • Migrating from 1.x to 2.0
    • Roadmap
    • Changelog
    • Alternatives
Powered by GitBook
On this page

Was this helpful?

  1. Guides

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 %}
PreviousTwig CookbookNextInternationalization

Last updated 2 years ago

Was this helpful?