Advertisement
krot

Create Smarty plagin

Jan 19th, 2017
259
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 2.13 KB | None | 0 0
  1. Step 1: Name Your Plugin and Add a Header
  2.  
  3. To start, you’ll need an empty PHP document. And then, in PHP comments, we add simple code which describes the plugin.
  4.  
  5. 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.
  6.  
  7. <?php
  8. /*
  9.  * Smarty plugin
  10.  * -------------------------------------------------------------
  11.  * File:     function.vbchecker.php
  12.  * Type:     function
  13.  * Name:     vbchecker
  14.  * Purpose:  check string length and outputs a response
  15.  * -------------------------------------------------------------
  16.  */
  17. Step 2: Write Your Function
  18.  
  19. 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.
  20.  
  21. function smarty_function_vbchecker($params, &$smarty)
  22. {
  23.     $length = strlen($params['vbstring']);
  24.     $output = "Your sentence is too long. Shorten It!";
  25.     if($length < 50)
  26.         $output = "Your sentence is just right!";
  27.    
  28.     return $output;
  29. }
  30. ?>
  31.  
  32. And there you have it. You will notice that we referenced an external variable via the $params array.
  33. Step 3: Save It In The Plugins Folder
  34.  
  35. 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 )
  36.  
  37. Be sure to save the plugin according to the file name that you specified in the header of your plugin.  
  38.  
  39. And that’s it! All that is left to do is use the new function in your template.
  40. Calling Your New Function Within Your Template
  41.  
  42. 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:
  43.  
  44. {vbchecker vbstring='See, it is very easy to write a function.'}
  45.  
  46.  
  47.  
  48. Obviously, this is a very simple example, but using these steps you can create very useful custom functions for your templates.
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement