<?xml version="1.0" encoding="UTF-8"?> <rss version="2.0" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:wfw="http://wellformedweb.org/CommentAPI/" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:sy="http://purl.org/rss/1.0/modules/syndication/" xmlns:slash="http://purl.org/rss/1.0/modules/slash/" ><channel><title>ViralPatel.net &#187; Smarty</title> <atom:link href="http://viralpatel.net/blogs/category/php/smarty/feed" rel="self" type="application/rss+xml" /><link>http://viralpatel.net/blogs</link> <description>Tutorials, Java, J2EE, Struts, AJAX, JavaScript, CSS, Web 2.0, MySQL, Articles</description> <lastBuildDate>Tue, 24 Jan 2012 13:45:10 +0000</lastBuildDate> <language>en</language> <sy:updatePeriod>hourly</sy:updatePeriod> <sy:updateFrequency>1</sy:updateFrequency> <generator>http://wordpress.org/?v=3.3.1</generator> <item><title>Smarty templates: Creating smarty custom functions</title><link>http://viralpatel.net/blogs/2009/06/smarty-templates-creating-smarty-custom-functions.html</link> <comments>http://viralpatel.net/blogs/2009/06/smarty-templates-creating-smarty-custom-functions.html#comments</comments> <pubDate>Wed, 03 Jun 2009 08:43:17 +0000</pubDate> <dc:creator>Viral Patel</dc:creator> <category><![CDATA[PHP]]></category> <category><![CDATA[Smarty]]></category> <category><![CDATA[agots]]></category> <category><![CDATA[smarty custom functions]]></category> <category><![CDATA[smarty templates]]></category><guid isPermaLink="false">http://viralpatel.net/blogs/?p=1355</guid> <description><![CDATA[Yesterday I wrote an article about a php method that can convert normal timestamp into &#8220;x Min Ago&#8221; like timestamps. I will call these type of timestamps an &#8220;agots&#8220;. 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 [...]]]></description> <content:encoded><![CDATA[<p><img src="http://img.viralpatel.net/2009/06/smarty-custom-function.png" alt="smarty-custom-function" title="smarty-custom-function" width="220" height="175" class="alignleft size-full wp-image-1356" />Yesterday <a href="http://viralpatel.net/blogs/2009/06/twitter-like-n-min-sec-ago-timestamp-in-php-mysql.html"><strong>I wrote an article</strong></a> about a php method that can convert normal timestamp into &#8220;x Min Ago&#8221; like timestamps. I will call these type of timestamps an &#8220;<strong>agots</strong>&#8220;. Although the PHP method is straight forward in converting unix timestamps to <strong>agotimestamps</strong>, I thought of implementing a custom function in smarty that can be used anywhere in your smarty template to generate <strong>agots</strong>.</p><p>Let us first see the basics of Smarty Custom Functions.</p><h2>What is Custom Function in Smarty?</h2><p><strong>Smarty</strong> 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. <strong>Custom functions</strong> 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.</p><h2>Creating a Custom Function</h2><p>As mentioned in previous section, creating <strong>custom function</strong> in smarty is straightforward. Follow the three steps process and there you have your own <strong>smarty custom function</strong>.</p><h3>Step 1: Name the plugin and add a Header</h3><p>Create an empty PHP file and add a commented header to the PHP file. In our case the custom function name will be <strong>agots</strong>, so following will be the header.</p><pre class="brush: php; title: ; notranslate">
/*
 *     Smarty plugin
 * -------------------------------------------------------------
 * File:     	function.agots.php
 * Type:     	function
 * Name:     	agots
 * Description: This TAG creates a &quot;x minute ago&quot; like timestamp.
 *
 * -------------------------------------------------------------
 * @license GNU Public License (GPL)
 *
 * -------------------------------------------------------------
 * Parameter:
 * - ts     	= the email to fetch the gravatar for (required)
 * -------------------------------------------------------------
 * Example usage:
 *
 * &lt;div&gt;{agots ts=&quot;3434323&quot;} ago &lt;/div&gt;
 */
</pre><p>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.</p><h3>Step 2: Write your PHP custom function</h3><p>Once the header is ready, all you have to do is write the PHP function. In our case we have written <strong>agots</strong> function.<br /> One thing you have to take care here is that all smarty custom function names must start with &#8220;<strong>smarty_function_</strong>&#8220;. Thus our agots function&#8217;s name will be smarty_function_agots. Also all smarty custom functions must be defined with two parameters <code>$params</code> and <code>&#038;$smarty</code>. 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 <code>$params['ts']</code> in our custom function.</p><pre class="brush: php; title: ; notranslate">
function smarty_function_agots($params, &amp;amp;$smarty) {

	if(!isset($params['ts'])) {
		$smarty-&gt;trigger_error(&quot;gravatar: neither 'email' nor 'default' attribute passed&quot;);
		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 &lt; $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 : &quot;$count {$name}s&quot;;

	if ($i + 1 &lt; $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 : &quot; $count2 {$name2}s&quot;;
		}
	}
	return $print;
}
</pre><h3>Step 3: Save the custom function in Plugins directory</h3><p>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 <strong>plugins</strong> 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.<custom_function>.php.</p><h2>Calling the custom function</h2><p>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:</p><pre class="brush: php; title: ; notranslate">
{agots ts='2451254'}
</pre><p>You may want to pass the value of smarty variable to our custom function.</p><pre class="brush: php; title: ; notranslate">
{agots ts=$myunixtimestamp}
</pre><p>Above is a simple example to create your own custom function in smarty. You may extend this and add your own useful functions.</p><p><em>You may want to bookmark this article and share it with others.</em></p><div id="relatedpost"><h2  class="related_post_title">Related Posts</h2><ul class="related_post"><li><a href="http://viralpatel.net/blogs/2011/01/dynamic-unread-count-favicon-in-php.html" title="Dynamic unread count Favicon in PHP">Dynamic unread count Favicon in PHP</a></li><li><a href="http://viralpatel.net/blogs/2010/12/password-protect-your-webpages-using-htaccess.html" title="Password Protect your webpages using htaccess">Password Protect your webpages using htaccess</a></li><li><a href="http://viralpatel.net/blogs/2009/11/php-fatal-error-time-htaccess.html" title="PHP Fatal Error Maximum Execution Time Issue &#038; htaccess">PHP Fatal Error Maximum Execution Time Issue &#038; htaccess</a></li><li><a href="http://viralpatel.net/blogs/2009/09/how-to-setup-multiple-virtual-hosts-in-wamp.html" title="How to: Setup Multiple Virtual Hosts in WAMP Server">How to: Setup Multiple Virtual Hosts in WAMP Server</a></li><li><a href="http://viralpatel.net/blogs/2009/08/server-php-variable-php-self-server-request-uri.html" title="Knowing $_SERVER PHP Variable in a better way">Knowing $_SERVER PHP Variable in a better way</a></li><li><a href="http://viralpatel.net/blogs/2009/06/restful-web-service-tutorial-introduction-rest-restful.html" title="RESTful Web Service tutorial: An Introduction for beginners">RESTful Web Service tutorial: An Introduction for beginners</a></li><li><a href="http://viralpatel.net/blogs/2009/06/21-very-useful-htaccess-tips-tricks.html" title="21 very useful htaccess tips &#038; tricks">21 very useful htaccess tips &#038; tricks</a></li></ul></div>]]></content:encoded> <wfw:commentRss>http://viralpatel.net/blogs/2009/06/smarty-templates-creating-smarty-custom-functions.html/feed</wfw:commentRss> <slash:comments>3</slash:comments> </item> </channel> </rss>
<!-- Performance optimized by W3 Total Cache. Learn more: http://www.w3-edge.com/wordpress-plugins/

Minified using disk: basic
Page Caching using disk: enhanced

Served from: viralpatel.net @ 2012-02-09 03:28:18 -->
