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 iOS绕地区网络检测
  • ¥15 python验证码滑块图像识别
  • ¥15 根据背景及设计要求撰写设计报告
  • ¥15 QT6颜色选择对话框显示不完整
  • ¥20 能提供一下思路或者代码吗
  • ¥15 用twincat控制!
  • ¥15 请问一下这个运行结果是怎么来的
  • ¥15 单通道放大电路的工作原理
  • ¥30 YOLO检测微调结果p为1
  • ¥15 DS18B20内部ADC模数转换器