0
votes

I'm working on a new big PHP / Symfony 2 project and decided to use Sass / SCSS and Compass which I found both really awesome for managing CSS in a modern way. However, there's still one problem for which I couldn't find any answer: how to place PHP variables in original SCSS files and make them preserved in output CSS files?

This is not a detail, because without this functionality there's no way to interface Sass generated stylesheets with PHP, which could be really limitating in some big projects.

To be clear, and as a starting point, in a classic way we can interface CSS with PHP mainly like this :

<link type="text/css" href="layout.css.php?my_var=#CC0000" rel="stylesheet" />

and then in a pseudo CSS file layout.css.php like in the example above:

<?php header("Content-type: text/css");?>

.my_color {
  background-color:<?=$_GET['my_var']?>;
}

Now, how can I do something equivalent in SCSS / Compass? In other words, how to place some PHP vars in original SCSS files that will be kept as is in the final CSS output file, so that it could be further parsed in real time with PHP like in the example above?

When I try to do this Compass and SASS compilers fail because of the PHP syntax.

Phamlp has some filters for PHP that only apply to haml templates, not SCSS files.

LESSphp seems to have such functionality, but lots of people seem to be moving from LESS to SCSS / Compass, so what is the best approach?

Many thanks.

1

1 Answers

3
votes

I really don't think you want to do what you're trying to do.

One of the major advantages of languages like Sass, LESS, and Stylus (NB: I believe Stylus is a more powerful and flexible language than Sass) is that they preprocess down to bare CSS which can then be cached by browsers or distributed by a CDN. If you then run that otherwise-static content through PHP, you completely lose that advantage.

I believe in this day and age the correct way to have dynamically-styled content like you seem to be trying to achieve is to use Javascript: have your application deliver a static JS file, then augment it with dynamic data. In this example, you would have a function which asks the server "what is the user's preferred background color?" (either via an XMLHttpRequest or via looking at a JSON object delivered along with the original PHP-written page). Then it sets the appropriate properties on the appropriate element(s) or class(es) thereof, possibly using a helper library such as jQuery.

This approach has major advantages over server-side CSS generation (such as proper caching, a greater amount of server-side static content which means better site responsiveness, improved separation of concerns, greater ease of implementing alternate UIs since the server isn't setting display properties, ...) - and just about the only drawback is that it requires a JS-enabled browser. Please, consider it.