Damn! I’m hard coding all the project imagery assets within my stylesheets. What if the url to those image assets change? This is where Compass will come to the rescue.
To be completely frank, I almost completed an entire bowel movement upon discovery of this sneaky little helper I’m going to discuss. The story goes like this; work locally with your assets folder, upload your code and assets to the deployment server, test, and then finally make it production ready, but we’re missing one important aspect from this entire process; What happens if the location of those assets change –or– worse they’re moved to a cdn? Now you’ve gotta sift through hundreds, or even thousands of lines of code and swap out the url. Have no fear though as we can solve this problem in a non–trivial manner using a special compass helper called
Before I found the
image-url helper I was doing the following…
Executing the method in Figure 1, I only had to change the
$assets_path and call it a day, but that’s not good enough yet. Compass can do way better than my silly Sass variable. This approach only works if your images always rest within an
img directory, but it’s flawed for that very reason.
Lets take a look at the following examples to get a better understanding of this mysterious beast called
config.rb example above we’re including two very important helpers
relative_assets. Setting the value for
http_images_path will direct all your image assets to your production server, CDN or any other dark closet you’re hiding things in. It can also generate cache–busting query strings based on image timestamps. This will keep browser caches from displaying the wrong image if you change the image but not the url. If you don’t want this behavior, it’s easy to configure or disable.
Say I want to keep my images on a sub–domain, then all I would do is change the path like so…
and then in our
This will direct all my assets to the URL I’ve defined for
http_images_path…Hot Damn! that’s some sweet sauce. I could take this one step further and set the
relative_assets line to true while working locally like so;
relative_assets will now serve all the assets from your local assets/images directory that’s defined by your
config.rb file seen in Figure 6:
Pretty rad huh? we can also use a relative url based on our
Although this method works just fine I prefer to use
http_images_path and call it a day. Now that you have this nifty Compass helper down why not optimize those images and read my article on optimizing images with Grunt. As always, hit me up with any questions, comments, suggestions or rants.