I want to add icons to my application. I've put the icons in public_html/images/icons/ and I want a DRY way to put them in my view-scripts. So I'd preferably not repeat..
<img src="<?php echo $this->baseUrl();?>/images/icons/plus-circle.png"</a>
..for every icon. I'd prefer a simple object+function call. What is a best practice for this?
I suspect I should use a vi开发者_StackOverflowew helper, but I don't understand those fully yet.
Thanks!
I would use an View Helper for this.
class My_View_Helper_Icon extends Zend_View_Helper_Abstract
{
public function icon($icon)
{
// not sure if you can use $this->baseUrl(); inside view helper
$baseUrl = Zend_Controller_Front::getInstance()->getBaseUrl();
$xhtml = sprintf('<img src="%s/images/icons/%s"', $baseUrl, $icon);
return $xhtml;
}
}
Inside your view
echo $this->icon('plus-circle.png');
I have a view helper which has the method $this->app()->getFileUrl('favicon.ico')
. Which will search the theme's location first then the public location. I assign this to a variable at the top of my view script and all done.
The source for the view helper and front controller plugin can be found here: http://github.com/balupton/balphp/tree/master/trunk/lib/Bal/
Or rather the code directly: http://github.com/balupton/balphp/blob/master/trunk/lib/Bal/Controller/Plugin/App/Abstract.php#L721
Using @ArneRie's answer:
In views/helpers/Icon.php I've written the following class:
class Zend_View_Helper_Icon extends Zend_View_Helper_Abstract
{
//$icon is the name of an icon without the ".png" at the end because all icons
//are .png
public function icon($icon)
{
$baseUrl = Zend_Controller_Front::getInstance()->getBaseUrl();
return sprintf('<img src="%s/images/icons/%s.png">', $baseUrl, $icon);
}
}
In my view file in views/scripts/index/index.phtml I then call the method of the Icon object like so:
<?php echo $this->icon('plus-circle');?>
Here is my version:
class My_View_Helper_Icon extends Zend_View_Helper_HtmlElement
{
/**
*
* @param string $src Icon source
* @param array $attribs HTML Atrtibutes and values
* @param string $tag HTML tag name
* @return string HTML
*/
public function icon($src, $attribs = array(), $tag = 'img')
{
$attribs['src'] = $this->view->baseUrl($src);
$html = '<' . $tag . $this->_htmlAttribs($attribs) . $this->getClosingBracket();
return $html;
}
}
精彩评论