Site Cloner PHP Script
Bargain Hunter PHP Script
Job Hunter PHP Script
Site Login and Access Control PHP Script

Functions and Smarty Template Tutorial

Whether you build a simple website or web application with Smarty, you want to use functions. With Smarty, you have two options for which you can use them.

For one, you can code them into your existing ‘.php’ file and use them from there since a function will will either output a print statement, or return a string or array.

Your second option is to call them from within the design(.tpl) file. You are able to successfully call and use functions using the Smarty {insert} tag. An example is shown below.

Function

This simple function will print the text Hello World, create a variable called $new_world and return it from the function. All functions will have ‘smarty_insert_‘ precede the actual function name, which in this case is called hello_world.

 <?php  
function smarty_insert_hello_world(){ 
echo "Hello world"; 
$new_world = " is returned "; 
return $new_world; 
}

.php File

The ‘.php’ file includes a template header, main file and footer file. The function.tpl is the one which is relevant for this tutorial and its usage will explained.

include("libs/smarty.class.php"); 
$smarty = new Smarty ();  
$smarty->display("includes/header.inc.tpl"); 
$smarty->display("function.tpl");  
$smarty->display("includes/footer.inc.tpl");  
?>

.tpl File

The {insert} tag below will call the function hello_world from the file functions.inc. After that, the returned variable will take on the name {$function_tag_name}.

 <p> {insert name="hello_world" assign="function_tag_name" script="functions.inc"} {$function_tag_name} from the function. </p>

Output

The second line of output came from the ‘.tpl’ file. The top and bottom lines are just the header and footer file where the main menu and footer file can be created for all pages of the web application.

Add Header Code HereHello world is returned from the function.

Add Custom Footer