Skip to content

Instantly share code, notes, and snippets.

@merk
Last active May 16, 2019 16:42
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save merk/7668680 to your computer and use it in GitHub Desktop.
Save merk/7668680 to your computer and use it in GitHub Desktop.
Overridden GlobalVariables object to add more to the twig {{ app }} global variable
<?php
use Symfony\Component\HttpKernel\Kernel;
use Symfony\Component\Config\Loader\LoaderInterface;
class AppKernel extends Kernel
{
// ....
protected function getKernelParameters()
{
$parameters = parent::getKernelParameters();
$parameters['app.version'] = trim(shell_exec('git describe --tags --always'));
return $parameters;
}
}
parameters:
templating.globals.class: Project\AppBundle\Twig\GlobalVariables
<?php
/**
* This file is part of the PROJECT
*
* (c) Infinite Networks Pty Ltd <http://www.infinite.net.au>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Project\AppBundle\Twig;
use Symfony\Bundle\FrameworkBundle\Templating\GlobalVariables as BaseGlobalVariables;
use Symfony\Component\DependencyInjection\ContainerInterface;
/**
* An extended value object to store additional global variables to be accessed
* in Twig.
*/
class GlobalVariables extends BaseGlobalVariables
{
/**
* Stores breadcrumbs for display.
*
* @var \SplQueue
*/
public $breadcrumbs;
/**
* Stores the current request time.
*
* @var \DateTime
*/
public $date;
/**
* Stores an array of date formats to be used inside twig.
*
* @var array<string>
*/
private $formats;
public function __construct(ContainerInterface $container)
{
parent::__construct($container);
$this->breadcrumbs = new \SplQueue;
$this->date = new \DateTime;
}
public function getFormats()
{
if (null === $this->formats) {
$this->formats = array(
'date' => $this->container->getParameter('format.date'),
'datetime' => $this->container->getParameter('format.datetime'),
'shortdate' => $this->container->getParameter('format.shortdate'),
'shorttime' => $this->container->getParameter('format.shorttime'),
'time' => $this->container->getParameter('format.time'),
);
}
return $this->formats;
}
/**
* Returns the application name
*
* @return string
*/
public function getName()
{
return $this->container->getParameter('app.name');
}
/**
* Returns the applications short name.
*
* @return string
*/
public function getShortName()
{
return $this->container->getParameter('app.short_name');
}
/**
* Returns the detected version of the application.
*
* @return string
*/
public function getVersion()
{
return $this->container->getParameter('app.version');
}
}
@NickTaporuk
Copy link

Thank you very much

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment