<?php
namespace ATL\CommonBundle\Twig;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
class PathExtension extends \Twig_Extension
{
private $generator;
private $container;
function __construct(UrlGeneratorInterface $generator, ContainerInterface $container)
{
$this->generator = $generator;
$this->container = $container;
}
public function getName()
{
return "path";
}
public function getFunctions()
{
return array(
'path' => new \Twig_Function_Method($this, 'getPath')
);
}
public function getPath($route, $parameters = array(), $relative = false)
{
$router = $this->container->get("router");
$locale = $this->container->get("request")->getLocale();
$routes = array_keys($router->getRouteCollection()->all());
if (!in_array($route, $routes) && in_array($route . '_' . $locale, $routes)) {
$route = $route . "_" . $locale;
}
return $this->generator->generate($route, $parameters, $relative ? UrlGeneratorInterface::RELATIVE_PATH : UrlGeneratorInterface::ABSOLUTE_PATH);
}
}
atl.twig.path_extension:
class: ATL\CommonBundle\Twig\PathExtension
arguments:
router: "@router"
container: "@service_container"
tags:
- { name: twig.extension }
Everything is same in the twig files. For example, if you have a route that does not have any relation with translation like admin just use:
admin:
pattern: /admin
defaults: { _controller: ACMEDemoBundle:Admin/Default:index }
But you have translation aware route like register than use like that:
site_register_tr:
pattern: /ajax/kayit-ol
defaults: { _controller: ACMEDemoBundle:Register:register }
site_register_en:
pattern: /ajax/register
defaults: { _controller: ACMEDemoBundle:Register:register }