Using LESS with Symfony2

Craig Blanchette on Google+ on December 19th 2012

Using LESS can save you a lot of time when developing websites. This tutorial is to show you how to add LESS support to your Symfony2 project, and integrate it with Assetic. The LESS compiler that I always use is called lessphp. The first thing you'll want to do is include lessphp into your vendors folder using composer:

composer.json
  1. ...
  2. "require": {
  3. ...
  4. "leafo/lessphp": "dev-master",
  5. ...
  6. }
  7. ...
Now it's time to download the package:
php composer.phar update leafo/lessphp


After you've downloaded lessphp, it's time to add it to Assetic:

app/config/config.yml
  1. assetic:
  2.   filters:
  3.   cssrewrite: ~
  4.   lessphp:
  5.   apply_to: "\.less$"
  6. # Formatter options: compressed, lessjs, classic
  7.   formatter: "compressed"
  8.   preserve_comments: false
  9.   presets:
  10.   my_variable: "#000"

This lets Assetic know to apply this filter to all files ending in ".less" Now that this is all setup, you can use Assetic's stylesheet tags to compile your LESS. I prefer to put my LESS files in Acme/Bundle/SampleBundle/Resources/less. It's really not necessary to put your LESS files in your public folder because they do not need to be visible to the public, they will always be compiled first.

You can change how lessphp minify's your code by the formatter option and the preserve comments option.

If you add presets to the configuration, you'll also be able to use those variables in your LESS files the way you would any LESS variable: "@my_variable" would now be "#000" in your LESS files. If you would like to add variables yourself through dependency injection, you can change the parameter "assetic.filter.lessphp.presets". Check out the configuration on GitHub.


  1. {% stylesheets '@AcmeSampleBundle/Resources/less/styles.less' %}
  2. <link rel="stylesheet" href="{{ asset_url }}">
  3. {% endstylesheets %}


It's important to note that you do not need to put the filter="lessphp" on the stylesheets tag. I also like to use filter="cssrewrite" as well, which works as expected.