gpt4 book ai didi

symfony - 如何更改 Twig 模板的路由生成中使用的主机?

转载 作者:行者123 更新时间:2023-12-01 23:23:25 28 4
gpt4 key购买 nike

好的,所以我有一个带有 Action 的 Controller 和与之关联的 2 条路由:

/**
* @Route("/index/preview/", name="mybundle.preview_index")
* @Route("/", name="mybundle.index")
* @Template
*/
public function indexAction(Request $request)
{
$preview = ($request->get('_route') === 'mybundle.preview_index');
$host = $request->getHttpHost(); //domain.com
if(!$preivew){
$host = 'domain2.com';
}
return array(
'preivew' => $preview,
'host' => $host,
'basePath' => $preview?'mybundle.preview_':'mybundle.',
);
}

然后我想根据主机在 Twig 模板中生成一条路由:

{{ path(basePath~'index') }}
//Then somehow pass the host to this so that i get the intended domain

如果我使用预览路线访问这条路线,那么我会得到:

domain.com/index/preview/

但如果我不是,它会给我:

domain2.com/

我尝试过的

  • 在 Controller 中设置路由器上下文,但这不会改变在 twig 中生成的路由

最佳答案

我想通了。而不是使用 path() 我必须使用 url() 并在路由器的上下文中设置主机:

if(!$preview){
$context = $this->get('router')->getContext();
$context->setHost($host);
}

然后是 Twig :

{{ url(basePath~'index') }}

关于symfony - 如何更改 Twig 模板的路由生成中使用的主机?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25676593/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com