Skip to content

CSS views in Squatting

December 23, 2008

From my earlier post today you will probably have noticed a problem with CSS files when something like following is used….

body {
	background: url( /images/some_image.gif );
}

What we want this to be is otherwise it won’t find that image file in your static folder…

body {
	background: url( [% Static %]/images/some_image.gif );
}

This means we need to process a CSS template through a Squatting view (see Caveat).

Here’s one way we can do this…..


# Controller code.....
    C( 
        CSS => [ '/css' ],
        get => sub { 
            my $self = shift; 
            $self->headers->{'Content-Type'} = 'text/css'; 
            $self->render( '_app_css' );
        },
    ),

“_app_css.tt” is now your CSS template. The prefixed “_” in the $self->render stops it processing the layout view around it. The layout.tt should now have this line…

    <link rel="stylesheet" href="[% R('CSS') %]" type="text/css" media="screen" title="Demo" />

So when rendered to browser the HTML will look like this…..

    <link rel="stylesheet" href="/css" type="text/css" media="screen" title="Demo" />

So “/css” will call the CSS controller and render the template “_app_css.tt”.

And so Bob’s your Aunty ;-)

/I3az/

Caveat: And its a big caveat…. while its nice and could be very useful in lots of cases to serve up dynamic CSS, it is generally going to be a lot better to keep it as a static file and let Apache serve it up and gain all the cache benefits associated with this.

Two possible workarounds are….

  • Build static file from TT file. This could even be done when Squatting app is first started. Alternatively look at TT tpage & ttree to do this process manually
  • Put caching routines into your CSS View (eg. pre-build rendering, return 304 HTTP code).

NB.: Replace CSS with Javascript in everything above. Everything equally applies.

References

About these ads

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.

%d bloggers like this: