Assetic & LESS
In a previous post I wrote about LESS and how to set up a small development environment for it with PHP and Apache. If you use the Symfony framework it’s even simpler. There is a bundle called “Assetic” which is enabled by default in the Symfony Standard Edition. You can find the documentation for the bundle on github. I’ll show you how to use Assetic to convert LESS sheets to CSS automatically. You should have node.js and LESS installed where you want to try this.
At first you have to add the following lines to the header section of your Twig template:
<head> {% stylesheets '@MyBundle/Resources/public/less/main.less' filter='less' %} <link rel="stylesheet" type="text/css" media="screen" href="{{ asset_url }}" /> {% endstylesheets %} </head>
This snippet tells Symfony to load main.less from the given path, convert it to css and output a link tag with the url of the generated CSS file. It is possible to tell Symfony to create a static asset in a configurable directory, but you can also let Assetic compile the assetcs dynamically. Therefore you have to add some configuration options to your config file (if they aren’t already there):
assetic: debug: true use_controller: true filters: less: ~
Additionally you have to add a special route for Assetic to your routing configuration:
_assetic: resource: . type: assetic
Just reload your page and whatever you write in main.less should be visible on your site now.
If it isn’t you can probably find an error message if you look at the source code of the generated web page. There should be the link tag with an auto-generated url like this:
<link rel="stylesheet" type="text/css" media="screen" href="/myexample/web/app_dev.php/css/b225231_main_1.css" />Open this url in your web browser and see what’s in there. A common error is:
Error: Cannot find module 'less'
This happens if node.js doesn’t know where to look for it’s libraries. In that case you can add another configuration option in order to tell node.js where the libraries are saved:
filters: cssrewrite: ~ less: node_paths: [ "/usr/lib/node_modules" ]
You can even use a placeholder to make things easier when you want to deploy your project on a production server. This way you can define node_paths in your parameters.ini:
filters: cssrewrite: ~ less: node_paths: [ %node_paths% ]
