Smarty Templates: How To Create Custom Functions

Smarty, the popular template engine that serves as a basis for many well-known content management systems such as Xoops, MovableType, and X-Cart, is full of great features. But it is not the most intuitive system for developers to learn to use, and it doesn’t help that the documentation is a bit scanty in spots. So here is the simplest and most complete tutorial you will find on writing a custom function for your Smarty templates.

Why You Need To Write Custom Functions

For most purposes, the built-in Smarty functions are sufficient. But sometimes, you will want to embed a custom function in your templates in order to define certain variables or display certain content. Now if you are wondering why you can’t just use PHP directly in your template, it is because there are some limitations on what you can do.

Yes, you can insert PHP into Smarty templates. You’d do it like this:

{php}
//php code here
echo "Hello World"; //prints out Hello World
{/php}

However, there are problems with this approach. Not only is this rather inelegant, but when you use PHP directly in your template, you defeat the purpose of using Smarty. But above all, there is one caveat: you cannot insert your own custom PHP functions directly within the php tags in a template. This is clearly a big problem for those of us who need to create customized components for a website.

But you can insert your own custom function if you create a Smarty function.

How To Create Your Own Smarty Function

Smarty makes it really easy to add a function. All you need to do is follow these 3 easy steps.

Step 1: Name Your Plugin and Add a Header

To start, you’ll need an empty PHP document. And then, in PHP comments, we add simple code which describes the plugin.

In this case, our plugin will get the length of a string that is passed to it and display output based on how long it is. And our plugin will be called vbchecker. See the sample code below.

<?php
/*
 * Smarty plugin
 * -------------------------------------------------------------
 * File:     function.vbchecker.php
 * Type:     function
 * Name:     vbchecker
 * Purpose:  check string length and outputs a response
 * -------------------------------------------------------------
 */

Step 2: Write Your Function

Next, write the body of your function. There is one thing to pay attention to: all Smarty functions need to be preceded by "smarty_function_" in the function definition, as shown below. And, whether or not your function takes an input, you will always define it with two parameters: $params and &$smarty.

function smarty_function_vbchecker($params, &$smarty)
{
    $length = strlen($params['vbstring']);
    $output = "Your sentence is too long. Shorten It!";
    if($length < 50)
        $output = "Your sentence is just right!";
   
    return $output;
}
?>

And there you have it. You will notice that we referenced an external variable via the $params array.

Step 3: Save It In The Plugins Folder

Now, to add your new function to Smarty, you just need to save it in the plugins directory of your Smarty folder. (ie. Smarty-2.6.3 ⇒ plugins )

Be sure to save the plugin according to the file name that you specified in the header of your plugin.  

And that’s it! All that is left to do is use the new function in your template.

Calling Your New Function Within Your Template

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:

{vbchecker vbstring='See, it is very easy to write a function.'}

 

Obviously, this is a very simple example, but using these steps you can create very useful custom functions for your templates.

Tags: , , ,

13 Responses to “Smarty Templates: How To Create Custom Functions”

  • Gilberto Albino March 3, 2009 at 8:17 am

    Hey, very simple to understand your tutorial,
    but I got some questions.

    How can I interact with other functions?

    Let’s say I’ve created a function that gets the value from the database of my shopping cart information,
    and now I have a function that formats currency, as in 1000.00
    would become 1000,00.

    So How could I interact with both fictional getValues and formatValues functions?

  • mastershake August 14, 2009 at 6:49 pm

    dude, this little post made my life better. thanks. i really needed to use a chunk of php in some weird little xcart template tpl file, you saved me like hours upon hours

  • Ezekiel Victor September 25, 2009 at 2:19 am

    Gilberto, use the following within your custom function when requiring other functions:

    require_once($smarty->_get_plugin_filepath(‘function’, ‘html_options’));

    Of course, replace “html_options” with the name of your custom function.

    Hope this helps,
    Zeke

    • Ian October 8, 2009 at 3:14 pm

      But that only works for one function, right? On a big project I could dozens, or even hundreds. Is there a way to put multiple functions in one file?

      • Ezekiel Victor November 14, 2009 at 5:55 pm

        You use that to include access for one function. You can use it however many times you need to in a single file to include a variety of different Smarty functions. Ex:

        require_once($smarty->_get_plugin_filepath(‘function’, ‘myFunc1′));
        require_once($smarty->_get_plugin_filepath(‘function’, ‘myFunc2′));
        require_once($smarty->_get_plugin_filepath(‘function’, ‘myFunc3′));

        This would allow you to use smarty_function_myFunc1(…), smarty_function_myFunc2(…), and smarty_function_myFunc3(…) wherever you put those lines.

        • Ian November 16, 2009 at 10:34 am

          Thanks. I ended up just creating a class that contains all the methods I need, and then including that once, so it ends up being a lot cleaner than having to include every single function individually. If anyone’s interested the details are at http://fightingforalostcause.net/techblog/how-to-build-a-template-in-cms-made-simple-while-maintaining-sanity/

    • philonor October 9, 2012 at 3:58 am

      “require_once($smarty->_get_plugin_filepath(‘function’, ‘html_options’));”

      This does not work when there are multiple plugin paths.
      The correct way seems to me:

      $smarty->loadPlugin(‘html_options’);

  • Yaniv June 15, 2010 at 5:57 am

    Thank you for the simple explanation.

    I am thinking about changing my site from simple PHP pages to PHP pages using a framework, and Smarty looks the best option so far :-)

    thanks,
    Yaniv

  • isogashii August 10, 2010 at 10:13 am

    thank you,
    it was simple, and straight forward ;)

  • Jaya December 8, 2010 at 8:18 am

    Thank you !!
    This post was very helpful. I liked the ‘smart way’ in which you described smarty functions. I resolved a long pending issue.

    Thanks again. Cheers!

  • ET February 3, 2011 at 1:31 am

    Looks pretty straight forward but I thought I’d ask this question anyways…Can define multiple functions in a plugin?

  • rendra February 22, 2011 at 9:03 pm

    nice tutorial for dummies like me…

    very short and well explained on how to create custom functions on smarty

    Thank you

  • Sava September 29, 2012 at 6:38 pm

    Thank you, Thank you, Thank you, Thank you, Thank you…

Trackbacks

Trackback URL:

Leave a Reply

Want us to work on your project?

Contact us today for a quote. Click here to submit details regarding your project.

If you are making a general inquiry, send an email to info@velvetblues.com

Go Daddy Deal of the Week: Cheap .COM Domains! Offer expires soon!