N
N
Nikolai Egorov2018-04-02 18:03:45
symfony
Nikolai Egorov, 2018-04-02 18:03:45

How to properly load and display images in Symfony?

Learning Symfony 4 by making a blog and gallery.
The gallery has its own folder for uploading pictures, I specify it in the parameters:

parameters:
    upload_directory: '%kernel.project_dir%/public/up'

    gallery_upload: '%upload_directory%/gallery'
    documents_upload: '%upload_directory%/docs'
    files_upload: '%upload_directory%/files'

When uploading a picture, I save it in the controller using a simple FileUploader service - it saves the picture along the path that I pass as a parameter.
$uploadedFile = $request->files->get('image')['fileUploader'];
    $fileName = $fileUploader->upload($uploadedFile, $this->getParameter('gallery_upload'));
    $image->setImage($fileName);

Here I made the path pass through the parameter, and not through the constructor, in order to use the only FileUploader service for all downloads - where to save the file, we specify by passing the parameter. Is this correct, or does each type of file (document / invoice, archive, picture) need its own loader to load? In fact, the logic of the loader is the same - rename the resulting file and save it to the specified path. This is the first question.
The second one is related to displaying the image (and other types of files) in the Twig template engine. Using the example of a gallery, I get an image object and a file name in the template: But what is the correct way to pass the path to the file when it is displayed? Add additional parameters to the `parameters:` array, like:
<img src="/up/gallery/{{ image.filename }}">
parameters:
    gallery_web: '/gallery/'
    documents_web: '/docs/'
    files_web: '/files/'

As I understand it, in this case, you need to write a Twig extension that will request the desired parameter, such as:
<img src="{{ getParameter('gallery_web') }}{{ image.filename }}">

...or is there a prettier option?
Thank you in advance!

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question