Assetic with Less compilation in Symfony 3

Introduction

In this article I will explain how to install Assetic (not available in the standard edition since 2.8 version) in Symfony 3. For learn purposes I will explain how to do it in a single case scenario: compile less files and generate css.

Installation Steps

1. Install Assetic

As I have said before, since Symfony 2.8, Assetic will not be installed with de Standard Version, so we have to include it as a Bundle. To do this we will use Composer from our terminal:

This should install AsseticBundle. If you want to be sure that your bundle has been isntalled, you can go to your /vendor directory and look for a folder called vendor/symfony/assetic-bundle

Now we have to activate it in our Kernel.php file, so open your App/Kernel.php file and lets add a new array element:

2. Install Less Compiler

Now you have to install the LESS compiler. What is this? It is the “program” that will allows you convert your LESS code into CSS code. Let’s do it from the terminal:

Install the LESS library:

3. Configure Assetic

Now that we have installed Less, we have to tell our Symfony application where to find the binaries to compile our less code. Let’s do this in our App/config/config.yml file:

Here we are telling Assetic that the node binary is in /usr/local/bin/node and the modules are in /usr/local/lib/node_modules.

All is done, we can use Assetic to use our Less files.

Example of use

Now that we have explained how to install and config our Assetic with Less, an example is the best way to explain why this is so helpful.

What we are going to do now is configure Assetic in our view. Let’s see this piece of code:

Here we are telling assetic that we want to use the filter called less. Also, that we want to generate a file called css/main.css and that the less files to be  compiled and combined are located in @AppBundle/Resources/public/less/*. 

Now, for generate the CSS files, we have to execute this on the terminal:

If we want to generate the CSS files in prod environment, we have to execute this one:

Conclussion

In this article I have explained how to use LESS as CSS preprocessor in a Symfony 3 application. Following thois guide you should be able, also, to use SASS, CoffeeScript or any other filter that you want. If you have any comments on questions I will be happy to try to help you.

 

Symfony 3 Assetic Logo

2 thoughts on “Assetic with Less compilation in Symfony 3

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.