Tuesday, August 09, 2011

JSF Trick of the Day: CSS and EL

A perfect desktop image for CSS developersImage via Wikipedia
If you need to dynamically change CSS based on page location, you probably have seen something like this:
background-image: url('../../../../resources/images/background.gif');
You can remove all of the ../../../../ from the CSS by using Expression Language (EL) selectively in your CSS for example the above example can be modified to use the FacesContext to determine the location of an image resource from any page. See the example below.
background-image: url('#{facesContext.externalContext.requestContextPath}/resources/images/background.gif');
This will always have the correct path to the resources no matter how nested the pages are in your application. This same technique can be used to manipulate other CSS entries dynamically. This technique works on JSF 1.2 and JSF 2.0.

As a friend pointed out in the comments it can be shortened further. I want to make a point that this technique gives you access to the FacesContext object which gives you a lot more flexibility.
Enhanced by Zemanta


Popular Posts