Your Ad Here

How to write a custom Smarty function in php

In the interim between posts at waxjelly, we’ve collectively become addicted to Smarty. In addition to this, we’ve become addicted to extending and customizing smarty to do a bunch of crap that we find ourselves repeating, and essentially building our own custom framework on this humble-for-no-good-reason templating system. In this tutorial, we’ll write our first custom smarty, and get the ball rolling in the right direction for being able to do pretty much anything you want to do with … okay, this post is going to say “Smarty” a lot, in case you can’t already tell. Let’s get started.

  1. Locate your smarty plugins folder (mine is outside the document root, in the smarty/plugins directory)
  2. Create a new file and name it “function.waxjelly_hello.php”
  3. Create another file and name it “hello.tpl”
  4. Create a third file and name it “Index.php”

We’ll start by writing the index.php file, which will do the following:

  1. include the smarty class file
  2. instantiate an object of the smarty class
  3. set the path to our templates directory
  4. set the path to our compile directory
  5. set a smarty variable assignment
  6. display our class

Next, we’ll write our template file, which will do the following:

  1. call our custom smarty function
  2. pass it a static attribute
  3. pass it a smarty variable

Finally, we’ll write our custom smarty function, which will do the following:

  1. receive the parameters sent to it
  2. receive the global smarty object
  3. send an error to the smarty object if the required parameters are not set
  4. display the values of all received parameters in a basic format

Now that we’ve got that down, here are the files associated with this tutorial. Feel free to download, open up, and follow along, but keep in mind that there is some configuration in order to get it to work, which will all be covered in this post.

  1. index.php

    First, we include the smarty class file…

    include(PATH_TO_YOUR_SMARTY_FOLDER . ’smarty/Smarty.class.php’);

    Next, we instantiate the smarty object…

    $smarty = new Smarty();

    Now reset the template directory path…

    $smarty->templates_dir = PATH_TO_YOUR_TEMPLATES_FOLDER . ‘templates/’;

    … and reset the compile directory path…

    $smarty->compile_dir = PATH_TO_YOUR_COMPILE_FOLDER . ‘templates_c/’;

    Now that that’s done, we assign the variable that will be needed for this page…

    $smarty->assign(’name’, ‘Meshach’);

    Finally, we’re going to display the template file…

    $smarty->display(’index.tpl’);

  2. index.tpl

    In this file, we’re going to call the custom function, and pass it values for “greeting” and “name”.
    NOTE: the “name” attribute is being filled by the assigned variable from the index.php, and the greeting attribute is being hard-coded

    {waxjelly_hello greeting=’Hello’ name=$name}

  3. function.waxjelly_hello.php

    When we’re writing our custom smarty function, it’s name has to start with “smarty_function” and end with “_your_function_name“. All of the attributes are being passed into one array, which we’re calling “params”. We also include access to the parent smarty object with the nifty “&$smarty” var, which will let us pass it values for error messages without breaking the page load.

    function smarty_function_waxjelly_hello ($params, &$smarty) {

    This line of code makes “greeting” a required attribute, and sends an error through the smarty object if it’s not set…

    if (empty($params['greeting'])) {
    $smarty->_trigger_fatal_error(”[waxjelly_hello] param ‘greeting’ cannot be empty “);
    return;
    }

    …since we’re not requiring “name” as an attribute, we’re setting a default value for it if it’s not set

    if (isset($params['name'])) {
    $name = $params['name'];
    } else {
    $name = ‘(whoever you are).’;
    }

    … now we build a string to return to the page calling this function

    $return = ‘<div class=”myclass”>’;
    $return .= $params['greeting'] . ‘, ‘ . $name;
    $return .= ‘</div>’;

    Finally, we return the string, which will be compiled and echo’d

    return $return;

    }

That’s it! You’ve just written your first smarty plugin. We’ll be back with some more complex ones, but for now, enjoy cracking these things out to help your template-based site development. If you wanna get some ideas and inspiration (and very usable code in most cases), check out the smarty plugin directory.

Your Friend and Mine,
- Meshach

[digg=http://digg.com/programming/How_to_Write_a_Custom_Smarty_Function_in_PHP]

25 comments so far

  1. [...] from the WaxJeely blog today, there’s a post that steps you through the creation of a custom Smarty function in PHP. In this tutorial, we’ll write our first [...]

  2. smarty March 29, 2007 1:21 pm

    You can also create very easy modifier.

  3. Meshach March 30, 2007 9:34 pm

    Smarty, Thanks for the code. We’ll be writing a custom Smarty Modifier soon, as well as a codeblock, and some other nifty tools (including some cool AJAX and Smarty stuff!!). Thanks for your patience, we’ll get it out to you asap.

  4. Shin Zaiaku June 28, 2007 11:04 pm

    This helps out alot. I’ve been trying to figure out how to make a template system. If I’m understanding this right I could use variables like $header in a template and it will display a header for me?

  5. vivek lala July 17, 2007 5:28 am

    sir,please send tutorial of smarty to me.thanks

  6. AnferTuto July 28, 2007 3:59 pm

    Hola faretaste
    mekodinosad

  7. Visitor358 August 4, 2007 6:38 pm

    I have visited your site 626-times

  8. Visitor881 August 4, 2007 6:39 pm

    I could not find this site in the Search Engines index

  9. Music-Band August 5, 2007 4:50 pm

    Hey

    I was surfing the web and i saw this site, pretty cool.
    Currently im running and adult site:Reachton
    k, just want to say hi :)
    Can i link you from my site? im looking for quality content like yours. If no let me know if i can add u in exchange for a montly fee or something.

  10. johnpupu August 11, 2007 4:57 pm

    thx for yur article..
    it’s great helpful for me

  11. [...] reference… How to write a custom Smarty function in php [...]

  12. Visitor210 August 21, 2007 1:06 pm

    I have visited your site 711-times

  13. Visitor067 August 21, 2007 1:06 pm

    Your site found in Google: http://google.com/search?q=tem

  14. huzhangyou August 31, 2007 11:37 am

    Good Articles.

  15. Ulf Raharjo September 19, 2007 7:53 pm

    i’m losing my mind, and i don’t think it’s cleve. Ulf Raharjo.

  16. hernan September 29, 2007 3:36 am

    I love xtemplate as template engine for decoupling php logic from html generation, but smarty is ok.

    I wrote an article about the importance of using templates engine (smarty or xtemplate) en best php programming practices.. check it out (clicking my name).

  17. Eka Kolour October 21, 2007 9:05 pm

    oh lord my baby your driving me craz. Eka Kolour.

  18. JJ Smith October 23, 2007 1:53 pm

    Why would you create a new way to pass parameters to functions in php - ie with smarty all of the parameters are passed in an asociate array? That means if I have pre existing functions I regularly use, they have to be re-written to work the smarty way. Or I have to write a wrapper function for each function so I can use it in a smarty template. That makes life easier - not!

  19. admark November 2, 2007 9:56 pm

    I am just starting to understand smarty, so this article is very helpful.

  20. Souvik Roy November 21, 2007 6:51 am

    I try to Instal smarty in windows.But I am failure.
    Sir,please send tutorial of smarty to me.thanks

  21. naisioxerloro November 29, 2007 2:26 am

    Hi.
    Good design, who make it?

  22. Poedobongoott January 8, 2008 2:40 pm

    I really do like this place.
    Top earring links!

  23. Satya Prakash April 25, 2008 12:09 pm

    Good explanation.

  24. Satya Prakash April 25, 2008 2:54 pm
  25. Chico July 15, 2008 5:50 pm

    So simple, yet so helpful and useful. thanks for sharing this.

Leave a comment

Please be polite and on topic. Your e-mail will never be published.