Search code examples
symfonytwigsymfony-routing

How to change the Host used in route generation for a twig template?


Ok so i have a controller with an action and 2 routes associated with it:

/**
 * @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.',
    );
}

Then I want to generate a route inside the twig template depending on the host:

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

If I was accessing this route using the preview route then i would get:

domain.com/index/preview/

But if i wasnt it would give me:

domain2.com/

What I Have Tried

  • Setting the router context from within the controller, but that doesnt change routes generated in twig

Solution

  • I figured it out. Instead of using path() i have to use url() and set the host in the context of the router:

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

    Then twig:

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