如何更改树枝模板在路由生成中使用的主机?

Cha*_*ase 3 symfony twig symfony-routing

好的,所以我有一个带有动作的控制器和与之相关的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.',
    );
}
Run Code Online (Sandbox Code Playgroud)

然后我想根据主机在树枝模板内生成一条路由:

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

如果我使用预览路由访问此路由,则将得到:

domain.com/index/preview/
Run Code Online (Sandbox Code Playgroud)

但是,如果我不这样做,它将给我:

domain2.com/
Run Code Online (Sandbox Code Playgroud)

我尝试过的

  • 从控制器内部设置路由器上下文,但这不会更改树枝中生成的路由

Cha*_*ase 5

我想到了。不用使用,path()我必须url()在路由器的上下文中使用和设置主机:

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

然后是树枝:

{{ url(basePath~'index') }}
Run Code Online (Sandbox Code Playgroud)