Skip to content

Instantly share code, notes, and snippets.

@atolye15
Last active December 30, 2015 22:39
Show Gist options
  • Save atolye15/7895433 to your computer and use it in GitHub Desktop.
Save atolye15/7895433 to your computer and use it in GitHub Desktop.
Translate Aware Path Twig Method

PathExtension.php

<?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);
    }
}

services.yml

    atl.twig.path_extension:
        class: ATL\CommonBundle\Twig\PathExtension
        arguments:
            router: "@router"
            container: "@service_container"
        tags:
            - { name: twig.extension }

Usage

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 }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment