2 回答
TA贡献1799条经验 获得超9个赞
适用于 SF 4.4,使用注释:您可以声明双 @Route 注释,一个带有本地化路由,另一个没有本地化。如果与第一个注释不匹配,将使用非本地化路由。
* @Route({
* "fr": "/bonjour",
* "de": "/guten-tag"
* }, name="hello_path")
* @Route("/hello", name="hello_path")
TA贡献1839条经验 获得超15个赞
因此,经过相当多的调查后,似乎没有办法让它像 Symfony 的默认方法那样工作。
我采用了“解决方法”方法,并使用我自己的 Twig 函数扩展了 Symfony 的 Twig Bridge 的路由扩展autopath():
namespace App\Twig;
use Symfony\Bridge\Twig\Extension\RoutingExtension;
use Twig\TwigFunction;
// auto-wired services
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
use Symfony\Component\HttpFoundation\RequestStack;
/**
* Extends Symfony's Twig Bridge's routing extension providing more flexible localization.
*
* @author Kyeno
*/
class KyAutoPathExtension extends RoutingExtension
{
private $router;
private $request;
public function __construct(UrlGeneratorInterface $router, RequestStack $requestStack)
{
$this->router = $router;
$this->request = $requestStack->getCurrentRequest();
parent::__construct($router);
}
/**
* {@inheritdoc}
*
* @return TwigFunction[]
*/
public function getFunctions()
{
return [
new TwigFunction('autopath', [$this, 'getPathAuto'], ['is_safe_callback' => [$this, 'isUrlGenerationSafe']])
];
}
/**
* @param string $name
* @param array $parameters
* @param bool $relative
*
* @return string
*/
public function getPathAuto($name, $parameters = [], $relative = false)
{
// obtain current and default locales from request object
$localeRequested = $this->request->getLocale();
$localeDefault = $this->request->getDefaultLocale();
// build localized route name
// NOTE: Symfony does NOT RECOMMEND this way in their docs, but it's the fastest that popped in my mind
foreach([sprintf('%s.%s', $name, $localeRequested), sprintf('%s.%s', $name, $localeDefault)] as $nameLocalized) {
// if such route exists, link to it and break the loop
if($this->router->getRouteCollection()->get($nameLocalized)) {
return $this->router->generate($nameLocalized, $parameters, $relative ? UrlGeneratorInterface::RELATIVE_PATH : UrlGeneratorInterface::ABSOLUTE_PATH);
}
}
// when no matches found, attempt relying on Symfony Twig Bridge's original path() function
// (and likely fail with exception, unless they fix/allow it)
return parent::getPath($name, $parameters, $relative);
}
}
- 2 回答
- 0 关注
- 94 浏览
添加回答
举报