Answer the question
In order to leave comments, you need to log in
How to take locales for routes from the database?
https://symfony.com/doc/current/routing/service_co...
However, if the admin can change which locales? For example, if he adds a new locale?
# config/services.yaml
parameters:
app.locales: en|es // а мои локали идет из БД
Answer the question
In order to leave comments, you need to log in
As Minifets said , it’s difficult to do this through routing, it’s easier through event_dispatcher:
class SiteController
{
/**
* @Route(path="/{_locale}/", name="index_locale")
* @Route(path="/", name="index")
*/
public function indexAction(Request $request)
{
return new Response($request->getLocale());
}
}
namespace App\EventSubscriber;
use App\LocaleProvider;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpKernel\Event\GetResponseEvent;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Symfony\Component\HttpKernel\KernelEvents;
class LocaleSubscriber implements EventSubscriberInterface
{
/**
* @var LocaleProvider
*/
private $localeProvider;
public function __construct(LocaleProvider $localeProvider)
{
$this->localeProvider = $localeProvider;
}
/**
* @inheritDoc
*/
public static function getSubscribedEvents()
{
return [
KernelEvents::REQUEST => 'onKernelRequest',
];
}
public function onKernelRequest(GetResponseEvent $event)
{
if (!$event->isMasterRequest()) {
return;
}
$request = $event->getRequest();
if (!in_array($request->getLocale(), $this->localeProvider->getLocales())) {
throw new NotFoundHttpException(sprintf('Unknown locale %s', $request->getLocale()));
}
}
}
namespace App;
class LocaleProvider
{
public function getLocales()
{
return ['ru', 'en'];
}
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question