LESS CSS Assetic Configuration in a Symfony2 Project

I was having trouble getting LESS CSS (website here) configured properly in a project using Symfony2. Who better to ask for help than the man who wrote Assetic? So, i pinged Kris Wallsmith on IRC. He helped me out and asked me if I would write up a little post about how to correctly configure and use LESS within a Symfony 2 project and a Twig template.

In order for the LessFilter to work you must have Node.js installed. So head over here and install it if you have not already done so. You also have to install the LESS Node.js package. Read about that here under the “Server-side usage” heading.

Now that we have Node.js installed we can configure Assetic, so open up your config.yml and lets get to work. Here is my working configuration for LESS.

# app/config/config.yml
assetic:
    debug:          %kernel.debug%
    use_controller: false
    filters:
        cssrewrite: ~
        less:
            node: /usr/local/bin/node
            node_paths: [/usr/local/lib/node]
        yui_css:
            jar: %kernel.root_dir%/../java/yuicompressor-2.4.6.jar
        yui_js:
            jar: %kernel.root_dir%/../java/yuicompressor-2.4.6.jar

Your Node.js binary file may reside at a different path as well as the LESS Node.js extension. So, just be aware that those two parameters may be different on your machine. I am also compressing my output using the YUI Compressor.

Next, open up your base.html.twig file. Copy the following code into the head section:

{% stylesheets filter='less,?yui_css' '@MyBundle/Resources/less/site.less' %}
    <link href="{{ asset_url }}" rel="stylesheet" media="screen" />
{% endstylesheets %}

Here we have specified that we want to output stylesheets using the LESS filter and then compressing it with the YUI CSS compressor. Next we point it to the location of our LESS file.

Thats it. Enjoy.