Symfony2で Twig 関数の aseet や path のURLを絶対URLにする方法
Controller内であれば、generateUrl の第3引数を true にすることで絶対パスにすることができるが、Twig関数で生成したパスを絶対URLにする方法は多少調査した感じでは見当たらなかった。
symfony2 - How to get the full url for an asset in Controller? - Stack Overflow
で解決できるかと思ったが、
/app_dev.php などをパスに含めている場合うまくいかない。
そこで、Symfony\Component\HttpFoundation\Request
で他に使えるメソッドが無いか探したところ、以下を発見。
コード全体はHttpFoundation/Request.php at master · symfony/HttpFoundation · GitHub を参照。
/** * Gets the scheme and HTTP host. * * If the URL was called with basic authentication, the user * and the password are not added to the generated string. * * @return string The scheme and HTTP host */ public function getSchemeAndHttpHost() { return $this->getScheme().'://'.$this->getHttpHost(); }
getSchemeAndHttpHost() を使って、以下のように書くことができる。
path
{{ app.request.schemeAndHttpHost() ~ path('path_name') }}
asset
{{ app.request.schemeAndHttpHost() ~ asset('path/to/file') }}
twig から Request オブジェクトを参照する際は get を省けるようなので、 schemeAndHttpHost() でOK。