symfony Uncategorized

Add PHP code to Your CSS in Symfony

Hey, I’m inspired by this article today:

Of course approach used in this article is a bit overcomplicated and it wont work in symfony without changes.

So I was thinking how would I add custom PHP code into my symfony app’s CSS. First quick solution which came on my mind was to rename .css to .php and use custom PHP code where I need. Now when layout will include css it will fill it in with proper variable values (and even cache that code by symfony caching mechanism?).

But, in fact I’m wondering why this piece of code does not process php:


I believe it would process it automatically at some point 🙂

I like though the other approach which seems to me more flexible for usage:

RewriteRule ^(.*\.css)$ index.php?module=home&action=process_css&filename=$0

So we can have an action which would process requested CSS and customize it on the fly. Frankly, I did not try this but potentially I believe this approach has more advatanges than other ones.

How about you? Have you ever needed to customize your CSS on the fly?

3 replies on “Add PHP code to Your CSS in Symfony”

How about in routing.yml

url: /css/dynamic/:filename.css
param: { module: home, action: process_css }

You don’t have to touch htaccess, and you can retrieve the path like it was a normal link

<link href=”” rel=”stylesheet” type=”text/css” />

As far as I know, you can just create a route in your routing.yml file, add sf_format with “css” or “js” (!) to the mix and off you go.

Symfony already has support for css and js (it knows what content-type to send in these cases) so css and js files are plain and simple symfony actions here which can also be cached!

Cheers, Annis

PS: I’m doing this frequently when I need to internationalize a custom MooTools (JS framework) script of mine without much hassle. I’m staying flexible that way and I can cache it, so no performance impact there. 🙂

Leave a Reply

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