如何在 Controller 中获取资产的完整 url? [英] How to get the full url for an asset in Controller?
问题描述
我需要在控制器中生成一些 JSON 内容,我需要获取位于此处的上传图像的完整 URL:/web/uploads/myimage.jpg
.
I need to generate some JSON content in controller and I need to get the full URL to an uploaded image situated here : /web/uploads/myimage.jpg
.
我怎样才能得到它的完整网址?
How can I get the full url of it?
http://www.mywebsite.com/uploads/myimage.jpg
推荐答案
您可以从请求对象生成 url:
You can generate the url from the request object:
$baseurl = $request->getScheme() . '://' . $request->getHttpHost() . $request->getBasePath();
您可以制作一个 twig 扩展程序来剪切路径的 /web
部分,并使用该请求生成基本 url.
You could make a twig extension that cuts the /web
part of your path and uses the request to generate the base url.
参见 Symfony\Component\Routing\Generator\UrlGenerator::doGenerate
以获得更可靠的实现.
see Symfony\Component\Routing\Generator\UrlGenerator::doGenerate
for a more solid implementation.
此外,Twig 可以访问来自 app.request
的请求.
Also, Twig has access to the request from app.request
.
这篇关于如何在 Controller 中获取资产的完整 url?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!