Smarty templates: Creating smarty custom functions

smarty-custom-functionYesterday I wrote an article about a php method that can convert normal timestamp into “x Min Ago” like timestamps. I will call these type of timestamps an “agots“. Although the PHP method is straight forward in converting unix timestamps to agotimestamps, I thought of implementing a custom function in smarty that can be used anywhere in your smarty template to generate agots.

Let us first see the basics of Smarty Custom Functions.

What is Custom Function in Smarty?

Smarty comes with lots of inbuilt functions that can be used in our smarty templates and that provides rich set of APIs that can leveraged for easy creation of UI. Although sometimes we may need to create our own functionality and plug it in smarty so that it can be used across all smarty projects. So we can create our own custom smarty functions. Custom functions are nothing but a normal PHP function with a given function name and written in a given filename. We will see in next sections how exactly to write a custom function in smarty.

Creating a Custom Function

As mentioned in previous section, creating custom function in smarty is straightforward. Follow the three steps process and there you have your own smarty custom function.

Step 1: Name the plugin and add a Header

Create an empty PHP file and add a commented header to the PHP file. In our case the custom function name will be agots, so following will be the header.

/*
 *     Smarty plugin
 * -------------------------------------------------------------
 * File:     	function.agots.php
 * Type:     	function
 * Name:     	agots
 * Description: This TAG creates a "x minute ago" like timestamp.
 *
 * -------------------------------------------------------------
 * @license GNU Public License (GPL)
 *
 * -------------------------------------------------------------
 * Parameter:
 * - ts     	= the email to fetch the gravatar for (required)
 * -------------------------------------------------------------
 * Example usage:
 *
 * <div>{agots ts="3434323"} ago </div>
 */

In above header, the Name: attribute is the name of your custom function and the File: attribute is the file name where you are writing this function.

Step 2: Write your PHP custom function

Once the header is ready, all you have to do is write the PHP function. In our case we have written agots function.
One thing you have to take care here is that all smarty custom function names must start with “smarty_function_“. Thus our agots function’s name will be smarty_function_agots. Also all smarty custom functions must be defined with two parameters $params and &$smarty. The parameters that we pass in custom functions can be read through the associative array $params. In our case the parameter will be timestamp (ts) so we read this parameter as $params['ts'] in our custom function.

function smarty_function_agots($params, &amp;$smarty) {

	if(!isset($params['ts'])) {
		$smarty->trigger_error("gravatar: neither 'email' nor 'default' attribute passed");
		return;
	}
	//return $params['ts'];
    // array of time period chunks
    $chunks = array(
		array(60 * 60 * 24 * 365 , 'year'),
		array(60 * 60 * 24 * 30 , 'month'),
		array(60 * 60 * 24 * 7, 'week'),
		array(60 * 60 * 24 , 'day'),
		array(60 * 60 , 'hour'),
		array(60 , 'min'),
		array(1 , 'sec'),
    );

    $today = time(); /* Current unix time  */
    $since = $today - $params['ts'];

    // $j saves performing the count function each time around the loop
    for ($i = 0, $j = count($chunks); $i < $j; $i++) {

		$seconds = $chunks[$i][0];
		$name = $chunks[$i][1];

		// finding the biggest chunk (if the chunk fits, break)
		if (($count = floor($since / $seconds)) != 0) {
			break;
		}
	}

	$print = ($count == 1) ? '1 '.$name : "$count {$name}s";

	if ($i + 1 < $j) {
		// now getting the second item
		$seconds2 = $chunks[$i + 1][0];
		$name2 = $chunks[$i + 1][1];

		// add second item if its greater than 0
		if (($count2 = floor(($since - ($seconds * $count)) / $seconds2)) != 0) {
			$print .= ($count2 == 1) ? ', 1 '.$name2 : " $count2 {$name2}s";
		}
	}
	return $print;
}

Step 3: Save the custom function in Plugins directory

We are ready to deploy our custom function to Smarty. All you have to do is just copy the PHP file function.agots.php to plugins directory in smarty installation directory. Just make sure that the name of the plugin file is same as the name specified in file header. The good practice is to have name as function..php.

Calling the custom function

To call your new function, you simply reference it by its name within curly brackets. And if the function requires a parameter, like ours does, you’d call it like this:

{agots ts='2451254'}

You may want to pass the value of smarty variable to our custom function.

{agots ts=$myunixtimestamp}

Above is a simple example to create your own custom function in smarty. You may extend this and add your own useful functions.

You may want to bookmark this article and share it with others.



11 Comments

  • Php 21 June, 2010, 12:09

    Very good one. Cool :-)

  • Sandesh Magdum 12 April, 2011, 13:11

    I want to add meta tag’s keywords and description attributes dynamically.

    First I done it within include.inc.php and assigned the variables in template files.

    But after creating smarty function i can use it like:

    function smarty_function_metatag($params, &$smarty) {

    if(!isset($params[‘tmpl’])) {
    $smarty->trigger_error(“metatag: parameter ‘tmpl’ missing”);
    return;
    }
    else if(!isset($params[‘ttype’])) {
    $smarty->trigger_error(“metatag: parameter ‘ttype’ missing”);
    return;
    }

    $pfile = $params[‘tmpl’];

    switch ($params[‘ttype’]) {

    case ‘keywords':

    $array_keywords = array(
    ‘login’=>’Login,Extentia’,
    ‘faq’=>’FAQ,Extentia’,
    ‘news’=>’News,Extentia’,
    ‘contact’=>’Contact Us,Extentia’,
    ‘careers’=>’Careers,Extentia’,
    ‘forgot’=>’Forgot Password,Extentia’
    );

    if (array_key_exists($pfile, $array_keywords)) {
    return $array_keywords[$pfile];
    }

    break;

    case ‘description':

    $array_description = array(
    ‘login’=>’Login to Extentia,Extentia’,
    ‘faq’=>’FAQ about Extentia,Extentia’,
    ‘news’=>’News about Extentia,Extentia’,
    ‘contact’=>’Contact Us,Extentia’,
    ‘careers’=>’Careers at Extentia,Extentia’,
    ‘forgot’=>’Forgot Password,Extentia’,
    );

    if (array_key_exists($pfile, $array_description)) {
    return $array_description[$pfile];
    }

    break;
    }
    }

    Your post helped me a lot.

    Thank you Viral Patel.

  • Sandesh Magdum 12 April, 2011, 13:14

    Use above function like:

  • Craig 8 April, 2012, 2:40

    Thanks…I couldn’t remember the correct syntax. This is easier to understand than the smarty manual for this topic.

  • Craig 8 April, 2012, 2:49

    BTW, Section 2 of your example in the function definition, the ampersand is getting rendered as its “&’ entity form which might confuse someone new to PHP/smarty wondering why your example won’t work.

  • Crystal Wilson 25 April, 2013, 1:18

    This is awesome, you have saved me so much time and didn’t realize how easy it was to create Smarty plugin! Thank you.

  • zyli 19 May, 2013, 17:23

    i have listings.html, header.html
    and created myfunction in
    i created a function in libs/plugins
    when i use it in listings.html is working but in header.html just give me an empty space. any ideea why?
    Thanks

  • Keny 11 June, 2013, 0:53

    Nice man :)

  • AQAA 17 January, 2014, 2:34

    How to write this one ?

    $url="http://".$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];
    //echo $url;
    $sell="http://www.sneakermarket.com/sellitems.html";
    if($sell==$url)
    {
    echo $this->_tpl_vars['myobj']->getTpl('general','header1.tpl');
    
    }
    else
    {
    echo $this->_tpl_vars['myobj']->getTpl('general','header.tpl');
    }
    
  • transistor 18 January, 2014, 3:35

    I had to modify a shopping cart application built on smarty. Never used it before. With this tutorial I was quickly able to write a function to pull some info from the database and return it in the function. Many thanks.

  • Gomathi 13 April, 2014, 9:28

    Immediately I want forget password coding in smarty with database pleeeeeeeeeeee

Leave a Reply

Your email address will not be published. Required fields are marked *

Note

To post source code in comment, use [code language] [/code] tag, for example:

  • [code java] Java source code here [/code]
  • [code html] HTML here [/code]

Current ye@r *