Blog /Stylesheets in Facebook

October 10, 2008 20:19 +0000  |  Geek Stuff Software 1

I wrote a fun bit of code for doing Facebook apps and thought that I would share.

One of the big problems with Facebook's app system is styleising text. You can't include an external file because they won't let you. This leads a lot of designers to write their code directly into the style="" attribute in the HTML. This can get ugly fast, and is the reason external .css files exist in the first place.

To remedy this, you can create the usual .css file externally and then call this helper function to get the job done for you. If you have to use paths etc in it, you can even pass a key/value pair dictionary to it to swap out keywords so that a strings like this:

	background-image: url('http://domain.tld/path/to/some/image.png');

Can look like this:

	background-image: url('[[images]]/image.png');

The call for this type of thing would be just:

	print '
		<style type="text/css">
			'. Helper::css('myStyle', array('images' => 'http://domain.tld/path/to/some')) .'
		</style>
	';

Here's the soruce if you're interested:

<?



    /**
    *
    * Helper functions for the view
    *
    * \author Daniel Quinn (corporate at danielquinn.org)
    *
    */

    class Helper
    {

        /**
        *
        * Simple templating engine for cascading style sheets since
        * Facebook doesn't like the idea of including external .css
        * files.  Instead, we keep the files separate then call this
        * method with a series of key/value replacers if need be.
        *
        * \param  file  Full path for the css to include
        * \param  vars  A dictionary lookup of key value pairs to be
        *               replaced in \a file.
        *
        */
        public static function css($file, $vars = array())
        {

            $in = file_get_contents("$file.css");

            $src = array();
            $dst = array();

            foreach ($vars as $k => $v)
            {
                $src[] = '[['. $k .']]';
                $dst[] = $v;
            }

            return str_replace($src, $dst, $in);

        }

    }



?>

Not revolutionary, I know. But maybe it'll help somebody out there.

Comments

smyli
10 Oct 2008, 9:44 p.m.  | 

neato! if i EVER have to style a facebook app, i'm so using that. :D

Post a Comment of Your Own

Markdown will work here, if you're into that sort of thing.