Linking images in Code Igniter
on Sunday 17th February, 2008 Gabe speculated thusly…I’m a big fan of the PHP framework, CodeIgniter. However, until recently it has lacked an elegant way of nesting an image in an anchor tag. I had to resort to manually typing out HTML like this:
<a href="<?=site_url?>/controller/action"><img src="<?=base_url()?>/images/button.gif"></a>
CodeIgniter 1.6 has been released, quickly followed by 1.6.1. This includes an image helper. One is still unable to elegantly link images using CI’s helpers. If you want to be able to do something like this:
<?= anchor( 'controller/action', img( 'images/button.gif' )?>
You could just comment out line 117 in /system/helpers/url_helper.php but that means you are altering CI core, which is not a good idea. For a start it will be overwritten when you upgrade and it is an inelegant hack.
A better bet is to create your own helper file and use it to override CodeIgniter’s one. This is dead-simple, just create a file called MY_url_helper.php in the following location /system/application/helpers/. Note that the MY_ prefix is set in the config.php file under $config['subclass_prefix'] = 'MY_'; so if you have changed that setting you will need to adjust your file-name accordingly.
Then just copy and paste the following in to it:
< ?php if (!defined('BASEPATH')) exit('No direct script access allowed');
if (! function_exists('anchor'))
{
function anchor($uri = '', $title = '', $attributes = '')
{
$title = (string) $title; if ( ! is_array($uri))
{
$site_url = ( ! preg_match('!^\w+://!i', $uri)) ? site_url($uri) : $uri;
}
else
{
$site_url = site_url($uri);
}
if ($title == '')
{
$title = $site_url;
}
if ($attributes == '')
{
// $attributes = ' title="'.$title.'"';
}
else
{
$attributes = _parse_attributes($attributes);
}
return ''.$title.'';
}
}
?>
Tags: CodeIgniter, php, source code
You could just do:
'') )?>You could indeed pass an array to the third parameter of the function call. However, I felt that it should be unnecessary and inconvenient, I wanted to be able to pass a minimal number of parameters without breakage. It has been recognised as a bug and fixed in the SVN repository: http://codeigniter.com/bug_tracker/bug/4209/
[...] Linking images in Code Igniter [...]
Just noting that CodeIgniter 1.6.2 has been recently released and now fixes these issues.
[...] Linking images in Code Igniter [...]
[...] Linking images in Code Igniter [...]
This is great info to know.