首先,您是否在配置中正确定义了语言?例如,这是我的配置:
config/services.yaml:(用于默认值)
parameters:
locale: 'en'
app_locales: en|fr #|de|es|pt|
services:
# default configuration for services in *this* file
_defaults:
autowire: true
autoconfigure: true
bind:
$locale: "@=service('request_stack').getCurrentRequest().getLocale()"
$defaultLocale: "%locale%"
$listLocales: '%app_locales%'
配置/包/translation.yaml:
framework:
default_locale: '%locale%'
translator:
default_path: '%kernel.project_dir%/translations'
fallbacks:
- '%locale%'
配置/包/translation.yaml
framework:
default_locale: '%locale%'
translator:
default_path: '%kernel.project_dir%/translations'
fallbacks:
- '%locale%'
也许它对你没用,但是从 Symfony 4 开始,你可以在https://symfony.com/doc/current/routing.html#localized-routes-i18n之后像这样在路由中强制区域设置:
controllers:
resource: ../../src/Controller/
type: annotation
prefix:
en: /
fr: /{_locale}
de: /{_locale}
es: /{_locale}
pt: /{_locale}
requirements:
_locale: '%app_locales%'
defaults:
_locale: '%locale%'
如果你想用英语强制,你可以创建一个用英语强制的 EventSubscriber : services.yaml :
App\EventListerner\LocaleSubscriber:
arguments: ['%kernel.default_locale%']
tags: [kernel.event_subscriber]
应用\事件监听器
<?php
namespace App\EventListerner;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\Event\RequestEvent;
use Symfony\Component\HttpKernel\KernelEvents;
/**
* Set locale into session
* Class LocaleSubscriber
* @package App\EventSubscriber
*/
class LocaleSubscriber implements EventSubscriberInterface
{
private string $defaultLocale;
/**
* LocaleSubscriber constructor.
* @param string $defaultLocale
*/
public function __construct(string $defaultLocale = 'en')
{
$this->defaultLocale = $defaultLocale;
}
/**
* @param RequestEvent $event
*/
public function onKernelRequest(RequestEvent $event): void
{
/** @var Request $request */
$request = $event->getRequest();
if (!$request->hasPreviousSession()) {
return;
}
// Change here to force in english
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));
}
}
/**
* @return array
*/
public static function getSubscribedEvents(): array
{
return [
KernelEvents::REQUEST => [
['onKernelRequest', 20]
]
];
}
}