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 關注
- 129 瀏覽
添加回答
舉報