RSS

How to write a custom Smarty function in php

This entry was posted on Mar 14 2007

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]


29 Responses to “How to write a custom Smarty function in php”

  1. You can also create very easy modifier.


  2. 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.


  3. 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?


  4. sir,please send tutorial of smarty to me.thanks


  5. Hola faretaste
    mekodinosad


  6. I have visited your site 626-times


  7. I could not find this site in the Search Engines index


  8. 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.


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


  10. I have visited your site 711-times


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


  12. Good Articles.


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


  14. 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).


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


  16. 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!


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


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


  19. Hi.
    Good design, who make it?


  20. I really do like this place.
    Top earring links!


  21. Good explanation.


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


  23. Wow. How did anyone get this to work? The following line in index.php:

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

    incorrectly sets the templates_dir property instead of template_dir.


  24. I will suggest you to remove the black background.
    See even in comment i cannot see what am I typing. as font color is matching with the background color.


  25. Also fully black does not looks good in programming blog. just feedback!


  26. I’m trying to create a function in Smarty and found your tuturial on Google.

    My function should get language strings from a database. It should look something like this: {lang}lang.str.name{/lang}.

    How to I refer to ‘lang.str.name’ in the function code?


  1. 2 Trackback(s)

  2. developercast.com » Blog Archive » WaxJelly Blog: How to write a custom Smarty function in PHP
  3. smarty rawurldecode plugin ….. at 廢物!!!我的名字是廢物!!!

Post a Comment