Skip to content

How to use lesscss without NodeJs in Symfony2 with Assetic?

Jonathan Beurel2 min read

Today, we will talk about a little trick: How to use Less when node.js is not available on your server?

We will use the latest version of lessphp available at the time of writing this article. You can find the full list of tags on github : https://github.com/leafo/lessphp/tags.

Assuming Composer is already installed, run the following command from your console to complete the installation:

php composer.phar require leafo/lessphp:0.3.9

The composer require command adds lessphp package to the composer.json file from the current directory and executes a composer update command.

Then, we need to update our config file:

# app/config/config.yml

Assetic Configuration

assetic: filters: cssrewrite: ~ lessphp: apply_to: “\.less$” #file: %kernel.root_dir%/../vendor/leafo/lessphp/lessc.inc.php

Assetic will change the paths to our assets and breaks all links that use relative paths.
In order to prevent this, we use cssrewrite filter that parses CSS files and rewrites paths to reflect the new location.

We use the ‘apply_to’ option so we don’t need to specify the lessphp filter on the twig template.

‘file’ parameter is useless since this commit if we use Composer autoloading. (Thanks @stof)

Finally, you can include your less files in the template like this:

<!DOCTYPE html>
<html>
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

    <title>My WebSite</title>
    {% stylesheets 'bundles/acme/less/example.less' %}
    <link
      rel="stylesheet"
      type="text/css"
      media="screen"
      href="{{ asset\_url }}"
    />
    {% endstylesheets %}
  </head>
  <body>
    {% block body%}{% endblock %}
  </body>
</html>

Because of the latency between the new lesscss feature and his implementation in php, lessphp is not as good as the latter but it is possible to use it in most situations.

You can find more information on the lessphp website: http://leafo.net/lessphp/