douhuai2015 2016-02-02 19:47
浏览 56
已采纳

从控制器和twig模板获取图像文件夹URI

I moved all the public images of my website to a folder out of the web folder of symfony so it can be shared with other web applications. I created a symbolic link to this folder so it can be accessed from the web folder of the symfony application.

ln -s /absolute/path/to/images /path/to/symfony/application_01/web/images
ln -s /absolute/path/to/images /path/to/symfony/application_02/web/images

Etc... for all applications.

I'm looking for a method that would allow me to retrieve the images URI in my development environment on localhost as well as in my production environment on the remote web server.

I would like to be able to retrieve this URI from the twig template AND from the controller.

Basically (for my application_01 for instance):

In the development environment it would return:

http://localhost/images/my_image.jpg

In the production environment, it would return:

http://www.application_01.com/images/my_image.jpg

My problem is that I found lots of different ways to get URIs but I'm not totally clear about how Symfony manages them and what functions to use to have a global solution working in all cases.

What is the best way to achieve my goal?


EDIT

Specifically I found some SO answers to quite similar questions proposing to use the following functions:

$request->getScheme(); $request->getHttpHost();

That seems to correspond to the values or superglobals $_SERVER['REQUEST_SCHEME'] and $_SERVER['HTTP_HOST']

And I don't know if this is the proper way to get this information since this is linked to the current request received by the server.

Isn't there another way to get this info independently from the request currently processed by the server?

  • 写回答

1条回答 默认 最新

  • dpfwhb7470 2016-02-02 20:11
    关注

    Define the following url

    image_url: path: /images/{image}

    Then use it like this

    /** @var Router $router */
    $router = $this->get('router');
    $url = $router->generate('image_url', ['image' => 'my_image.jpg'], Router::ABSOLUTE_URL);
    

    $url now contains the absolute url to your image. And of course it's the best practice you can think of :)

    ----- Answer to your comment about app_dev.php We used this solution in our company months ago.

        preg_replace('#/(.+?)\.php)', '', $router->generate('my_url');
    

    http://techimho.com/index.php/2015/10/15/generate-production-url-in-dev-environment/

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 完全没有学习过GAN,看了CSDN的一篇文章,里面有代码但是完全不知道如何操作
  • ¥15 使用ue5插件narrative时如何切换关卡也保存叙事任务记录
  • ¥20 软件测试决策法疑问求解答
  • ¥15 win11 23H2删除推荐的项目,支持注册表等
  • ¥15 matlab 用yalmip搭建模型,cplex求解,线性化处理的方法
  • ¥15 qt6.6.3 基于百度云的语音识别 不会改
  • ¥15 关于#目标检测#的问题:大概就是类似后台自动检测某下架商品的库存,在他监测到该商品上架并且可以购买的瞬间点击立即购买下单
  • ¥15 神经网络怎么把隐含层变量融合到损失函数中?
  • ¥15 lingo18勾选global solver求解使用的算法
  • ¥15 全部备份安卓app数据包括密码,可以复制到另一手机上运行