:::: MENU ::::

Thursday, February 7, 2013

The bundling and minification that arrived with the latest .Net 4.5 framework is a great tool. For those web applications that are using the WebForms App_Themes folder to style an application, it won't quite work as well as it is capable of. The App_Themes folder will automatically render down all CSS files it finds in the folder and sub directories, so if you register these files in your bundle config you will end up with two versions of the stylesheet rendered down to the client.

So how do we dynamically register some CSS files in an App_Theme folder without the default files being rendered down to the client? The short answer is, you can't. The long answer is, we can with a bit of a work around.

If we take out the CSS files (including any images etc referenced by the style sheets) and move them to another folder, say AppTheme, put our files into a directory under the AppTheme folder with the same theme name, let's go with Default. We can now go and register these files in our bundle config. The default method for registering style sheets isn't quite going to cut it as that defines all the file locations at application load time and we're going to want to dynamically change this folder depending on the theme selected for the current request.

Luckily, we already have this capability in the default web optimisation library. We just need to use the DynamicFolderBundle class as follows:
 
bundles.Add(new DynamicFolderBundle("Style", "*.css"));
 
And then on the page where you register the bundle, you can just register it with the following:
 
<%: System.Web.Optimization.Styles.Render("~/AppThemes/" + this.Theme + "/Style") %>
 
Which tells the bundler to look under the AppThemes/{ThemeName} folder and register all the css files under the one bundle. It's also possible for the DynamicFolderBundle to search all the sub-directories for CSS files, but you'll want to be careful with that if you have styles that reference external files such as background images.