Where can I add assets in symfony 5?

Viewed 3202

I'm using symfony 5 and I have no idea where can I pu my css, js, images files.

I read many posts about it but none helped me...

I tried:

  • composer require symfony/asset
  • symfony console assets:install

Here is the way i am using asset function in my twig files:

<link rel="stylesheet" type="text/css" href="{{ asset('css/base.css') }}">

And yes I have a file at public/css/base.css... But when I inspect the result page, my line is replaced by:

<link rel="stylesheet" type="text/css" href="/css/base.css">

Did someone have any idea ?

Best regards,

1 Answers

If you're NOT using webpack (or webpack encore), your assets should be in your public folder which is the root of your public project. For example, if you have a file called style.css in public/css/style.css, you can access it in your browser with the url (assuming you use a local server started in the public dir) http://localhost:8000/css/style.css.

The Symfony asset component goal is to guess if your project is in a subdirectory and therefore to resolve the correct path. In order to use it in a Twig template with the previous imaginary file :

<link rel="stylesheet" href="{{ asset('css/style.css') }}">

The asset function will be able to produce the right path for your file.

If you're using webpack, the setup is a bit harder so if you don't I won't explain it here.

Related