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\Data\ArticleData;
use App\Entity\Article;
use App\Twig\Extension\SlugExtension;
use App\Utility\BreadcrumbsHelper;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
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%"})
class BlogController extends AbstractController

 More on Stackoverflow

» Comments

Privacy-focused with Commento. (Comment system added on 2019-10-17: be the first! 🥇)