Skip to main content

Symfony assets management: assets:install

!!! Warning: this post is almost 8 years old and was written when using previous versions of Symfony, so it may not apply to current versions. A lot has changed in Symfony assets management since then. Let us know if you need extra help.

In your Symfony application there are bound to exist many assets (JS, CSS, and so on) either created by you or provided by third-party bundles.

As part of your deploy procedure, you usually have to use some Symfony console command to actually make the assets available to the frontend of your application.

Let’s start with the most basic solution: the assets:install command.

assets:install

php app/console assets:install

This command is available in Symfony core, no extra bundle is required. So this is probably the first you should get to know.

It will search through all available bundles (including the ones in your application) for a /Resources/Public/ folder and copy the content into /web/bundles/[bundle-name]/.

For example, the file

/src/appBundle/Resources/Public/css/app.css

will be copied into

/web/bundles/appBundle/css/app.css

which makes it publicly available.

You can specify a different target path if you want. To see all available options for this command, you can run:

php app/console assets:install --help

Bonus: use asset() function for more happiness

So now you have all your assets available in the web folder and you can simply write this in a layout:

<link rel="stylesheet" src="/bundles/appBundle/css/app.css">

But I have a tip: with Twig, it’s better to use the asset() function, like this:

<link rel="stylesheet" src="{{ asset('bundles/appBundle/css/app.css') }}">

The asset() function does some interesting things.

The most obvious is that it builds the correct path according the app configuration (i.e. you may have your “web” folder named differently, or positioned in a subfolder of your site root).

But it can also add a version number to your assets to avoid caching problems, e.g. automatically convert your link into this:

<link rel="stylesheet" src="/bundles/appBundle/css/app.css?v2">

where the version number is changed only once in your configuration file.

Conclusions

The assets:install command is very simple and lacks many advanced features, but it’s a good start ad it may be all you need for a very simple Symfony application.

Shortly we will see some more sophisticated solutions.