Image Spriting in XHP
I want to share with you a quick XHP class you can build that will greatly abstract your image spriting. Image sprites are a great way to reduce the number of resources downloaded from your server, but they can be a hassle to maintain. If you already sprite your images then you might have a class that generates the styles for your images. Your API might look something like this:
ImageSprite::getSpriteHtml(ImageSprite::ICON_PHOTOS);
You can sprinkle those into your rendering and it’ll work just fine, but with XHP you can build a custom component that behaves more like an HTML img tag than a PHP class and generates your spriting code behind the scenes. Consider the follow XHP element:
class :ui:sprite extends :x:element { attribute :img; attribute bool usesprite = true; private static $_spriteMap = array( ‘‘/icons/apps.png’’ => ‘‘appIcon’’, ‘‘/icons/photos.png’’ => ‘‘photoIcon’’, ‘‘/icons/users.png’‘ => ‘‘userIcon’’, … ); protected function render() { $img = ; $src = $this->getAttribute(‘‘src’’); if ($this->getAttribute(‘‘usesprite’’) && isset(self::$_spriteMap[$src])) { $img->addClass($this->_spriteMap[$src]); $src = ‘‘/images/spacer.gif’’; } $img->setAttribute(‘‘src’’, $src); return $img; }}
Your CSS would then look something like this:
.imageSprite { background: url(‘‘/icons/sprite.png’’) no-repeat; display: inline-block; height: 16px; width: 16px;}.appIcon { background-position: 0 0;}.photoIcon { background-position: 0 -16px; height: 14px;}.userIcon { background-position: 0 -30px; width: 15px;}
Now you can intermix this element with your HTML and get code that looks like this:
<ul class="nave"> <li>