How to handle assets in Symfony 4

user3429660 picture user3429660 · Dec 25, 2017 · Viewed 15.6k times · Source

I am building an application with Symfony 4 and I'd like to follow the best practices for web assets. I use Encore/Webpack for SCSS and JS and it works well; the resulting JS+CSS are nicely stored in /public/build folder. I'm stuck at how to store and use static assets like images, movies, sounds.

Should images be stored in 'public/images' folder or in 'assets/images'?

And some followup questions:

If the images are stored in public/images, will I get any benefit if I pollute the templates with asset('...') calls?

If the images are stored in assets/images, then:

  • How are they moved into public/images to be served via http? ./bin/console assets:install did nothing, saying: '[OK] No assets were provided by any bundle.'.
  • How do I use them in SCSS? Via relative paths?

Regards,

Answer

Wouter J picture Wouter J · Dec 25, 2017

Should images be stored in 'public/images' folder or in 'assets/images'?

Everything in public/ is available through the browser. In here, only production ready and build things should be put. As your images don't need any processing (I assume), you can (should) indeed put the images there.

Now, assume you're needing to do some processing (e.g. ugly JPEG compression), you would put the images in assets/, do some processing and then put only the processed images in public/.

If the images are stored in public/images, will I get any benefit if I pollute the templates with asset('...') calls?

Yes, asset() doesn't have anything to do with Encore or asset build management. The only thing it does is fixing your URLs. This means that if you move your app to sub directories on your server (example.com/app/), the URLs will automatically adapt. Read more about it in the Asset component documentation.