Skip to content

jonocode – a developer's blog

I moved! –>

I’m sure there are a number of ways you can handle this. There are also tons of modifications you can do to make it more useful, or better adapted to your particular needs. This post will quickly illustrate one way to create a dynamic stylesheet in Symfony 1.2.

I just finished writing a module that allows my users to change their background color. So I thought I’d share a similar way of doing this with an example.

Create a new doctrine model. Since we’re keeping things simple, our style sheet will only have one editable element: the body tag’s background-image.

    identifier: string(255)
    background_color: string(255)

Add a fixture and load it up:


    identifier: "main"
    background_color: "#000000"
$ symfony doctrine:build-all-reload

The identifier will be the stylesheet’s name. You’ll see it in the route, which you’ll add now:


  url: /dynamiccss/:identifier.css
  param: { module: dynamiccss, action: render }

Create a new module:

$ symfony init-module frontend dynamiccss

This module will be used to render a dynamic style sheet. You’ll want to make sure it doesn’t render the layout, and that it returns a content type of ‘text/css’. So edit the actions file and add a preExecute() method. Of course, you’ll also need a method to fetch the style sheet and render it.


  public function preExecute()

  public function executeRender()
    $this->stylesheet = Doctrine::getTable('DynamicCSS')

Next we’ll add the template, which is at this point is very simplistic. You’ll need to have that ::getByIdentifier() method implemented in the DynamicCSSTable class, as well.


body {
  background-color: <?php echo $stylesheet->getBackgroundColor() ?>;


public static function getByIdentifier($identifier)
  return $this->createQuery('c')
    ->addWhere('c.identifier = ?', $identifier)->fetchOne();

Now you can add your dynamic style sheet to the view. Here is an example:


  stylesheets: [/dynamiccss/main.css: { raw_name: true }]

That “raw_name” option allows you to override the typical way of creating an asset’s file name.

Now whenever someone edits the background color for the “main” style sheet, from the database, the background color can change.

You’ll still need to add an interface for editing the background color (or however many other options you add). That is up to you.

Complaints? Pointers? Thought of a better way?

Please post.


Tags: ,

%d bloggers like this: