Inject locale's requirements in your Symfony routes

Published on 2019-08-01 • Modified on 2019-08-01

This is a feature that was introduced in Symfony 4.1. It allows to directly inject a parameter in a route requirement instead of putting raw values. In this case, for this website, the locales_requirements parameter contains %locale%|fr, where locale is the default locale "en". When you want to add a locale to your project, all you will have to do is to add it to this parameter. (and translate everything of course 😁). Note that this annotation is declared at the controller level, therefore all actions declared in this one inherit from those requirements.

<?php declare(strict_types=1);

// src/Controller/BlogController.php

namespace App\Controller;

use App\Controller\Post\Post13Trait;
use App\Controller\Post\Post26Trait;
use App\Controller\Post\Post51Trait;
use App\Controller\Post\Post59Trait;
use App\Controller\Post\Post82Trait;
use App\Data\ArticleData;
use App\Entity\Article;
use App\Twig\Extension\SlugExtension;
use App\Utility\BreadcrumbsHelper;
use Monolog\Logger;
use Pagerfanta\Adapter\ArrayAdapter;
use Pagerfanta\Pagerfanta;
use Symfony\Component\Form\FormFactoryInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\Validator\Validator\ValidatorInterface;

 * @Route("/{_locale}/blog", name="blog_", requirements={"_locale"="%locales_requirements%"})
final class BlogController extends AbstractController