Access CodeIgniter helpers from Smarty templates

Written by: Phil Sturgeon

Hello, I am Phil and I have been developing websites since 1999. I started my career freelancing then ran a small web development team for over a year. Now I work as a developer for HargreavesLansdown and use my spare time to develop, write articles about programming and create slightly intoxicated screencasts. For more of my antics follow me on twitter @PhilSturgeon.

This article assumes you already have Smarty parsing your CodeIgniter views. If you have not done this, you can find out how to integrate Smarty with CodeIgniter here.

To access your CodeIgniter helpers from Smarty, all you need to do is make a new file in your “plugins/” directory called “helper.modifier.php” and paste in the following code:

<?php
/*
* Smarty plugin
* -------------------------------------------------------------
* File:     modifier.helper.php
* Type:     modifier
* Name:     helper
* Purpose:  Call CodeIgniter helpers from within Smarty.
* -------------------------------------------------------------
*/
function smarty_modifier_helper($string, $helper_file, $helper_func)
{
if (!function_exists("get_instance")) {
return "Can't get CI instance";
}

if (!function_exists($helper_func)) {
$CI =& get_instance();
$CI->load->helper($helper_file);
}

// Get all the params passed in as there might be a few
$params = func_get_args();

// String provided should be the first param and we dont want helper file or helper func being passed
$params[0] = $string;
unset($params[1]);

// Call the function with the params provided
return call_user_func_array($helper_func, array_values($params));
}
?>

Save that and try it out in one of your Smarty controlled view files. For example:

<p>Check out this amazing item</p> {$item.url|helper:'url':'anchor':$item.title:'class="more params"'}

With Smarty modifiers, the item you are modifying is the first param. The modifier is called after a pipe character “|” and then more parameters are separated by “:”. With this specific modifier, you list the helper, then the helper function, then as many params afterwards as you like.

Be the first to comment.

Tell us what you think !

Allowed tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>