【发布时间】:2021-01-08 21:22:22
【问题描述】:
我正在尝试使用 API Plateform 和 ReactJS 向我的应用程序添加多语言功能。 我已经安装了 StofDoctrineExtensionsBundle,我想使用扩展 Translatable。 我发送本地(“EN”或“FR”等)然后我想发送响应切换本地。
use Gedmo\Translatable\Translatable;
/**
* @ApiResource()
* @ORM\Entity(repositoryClass=CountryRepository::class)
*/
class Country implements Translatable
{
/**
* @ORM\Id
* @ORM\GeneratedValue
* @ORM\Column(type="integer")
*/
private $id;
/**
* @Gedmo\Translatable
* @ORM\Column(type="string", length=255)
*/
private $name;
services.yml
App\EventSubscriber\LocaleSubscriber:
arguments: ['%kernel.default_locale%']
LocaleSubscriber.php
<?php
namespace App\EventSubscriber;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpKernel\Event\RequestEvent;
use Symfony\Component\HttpKernel\KernelEvents;
class LocaleSubscriber implements EventSubscriberInterface
{
private $defaultLocale;
public function __construct(string $defaultLocale = 'en')
{
$this->defaultLocale = $defaultLocale;
}
public function onKernelRequest(RequestEvent $event)
{
$request = $event->getRequest();
if (!$request->hasPreviousSession()) {
return;
}
// try to see if the locale has been set as a _locale routing parameter
if ($locale = $request->attributes->get('_locale')) {
$request->getSession()->set('_locale', $locale);
} else {
// if no explicit locale has been set on this request, use one from the session
$request->setLocale($request->getSession()->get('_locale', $this->defaultLocale));
}
}
public static function getSubscribedEvents()
{
return [
// must be registered before (i.e. with a higher priority than) the default Locale listener
KernelEvents::REQUEST => [['onKernelRequest', 20]],
];
}
}
在允许我获取国家列表的网络服务的响应中,没有名称字段。
如何让国家名称切换语言? 谢谢。
【问题讨论】:
标签: symfony doctrine translation api-platform.com doctrine-extensions