You should create a Twig extension. At that link you can see how to create one and register it within Symfony. It doesn't show you how to define global through it but the process is really simple and described here.
Chewed down
Basically, you just need to create a class extending \Twig_Extension
. Then override default getGlobals
method in base extension class and provide your globals through it:
<?php
namespace MyBundle\Twig;
class MyTwigExtension extends \Twig_Extension
{
public function getGlobals()
{
return [
'current_year' => (new \DateTime())->format('Y'),
];
}
}
After that simply register it in your services.yml
or whatever format you're using:
services:
mybundle.twig.my_twig_extension:
class: MyBundle\Twig\MyTwigExtension
tags:
- { name: twig.extension }
Update based on comment
If you need to access that value in other parts of the code, it can be a bit more tricky, and there are a couple of ways of dealing with this.
My suggestion is that you create a service that will provide you the values you need:
<?php
namespace MyBundle\Util;
class CurrentYearProvider
{
public function getCurrentYear()
{
return (new \DateTime())->format('Y');
}
}
and register it as a service of course:
services:
current_year_provider:
class: MyBundle\Util\CurrentYearProvider
After that you should just inject it in twig extension:
services:
mybundle.twig.my_twig_extension:
class: MyBundle\Twig\MyTwigExtension
arguments: [@current_year_provider]
tags:
- { name: twig.extension }
And use it to fetch the value:
<?php
namespace MyBundle\Twig;
class MyTwigExtension extends \Twig_Extension
{
private $yearProvider;
public function __construct(CurrentYearProvider $yearProvider)
{
$this->yearProvider = $yearProvider;
}
public function getGlobals()
{
return [
'current_year' => $this->yearProvider->getCurrentYear(),
];
}
}
And if you need it in controller for example:
<?php
namespace MyBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
class MyController extends Controller
{
public function myAction()
{
$currentYear = $this->get('current_year_provider')->getCurrentYear();
}
}
This, however, seems quite silly if you just need to get current year. In my opinion.