【问题标题】:How to change the Host used in route generation for a twig template?如何更改树枝模板的路由生成中使用的主机?
【发布时间】:2014-10-29 20:37:12
【问题描述】:

好的,所以我有一个控制器,其中包含一个操作和 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/

我的尝试

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

【问题讨论】:

    标签: symfony twig symfony-routing


    【解决方案1】:

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

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

    然后是树枝:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-07-27
      • 2013-08-07
      • 1970-01-01
      • 1970-01-01
      • 2013-04-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多