For those newer to the Smarty Template Engine I thought I would make a simple example to help get started.
Download and Install
Download
Grab the Smarty example here. This is using the latest version as of this post, v2.6.22. Go here if you need an alternate version.
Install
Extract the downloaded archive to the document root of your web server. This is sometimes public_html if you have access to an FTP folder that is a level lower than the document root.
Folder Permissions
In order for the templates to compile the web server user must have write access to the doc_root/include/smarty/templates_c folder.
Move Include Folder (Optional)
If you need to install the include folder not in document root do the following:
Open include/config.php and change the $site_root variable to match the full path to where you are moving the include folder.
For example, you need to install in the folder test, which is one folder above document root.
doc_root/test/include
Change $site_root to:
$site_root = $_SERVER['DOCUMENT_ROOT'] . '/test';
Enable Caching (Optional)
If you want to enable caching to help with performance do the following:
Open include/config.php and change the caching setting.
// Enable caching
$smarty->caching = 1;
In order for caching to work the doc_root/include/smarty/cache folder must have write permission by the web server user.
Here is more information regarding the cache_dir directory.
Test
Fire up your favorite browser and check if the following shows up.
Smarty Variables
You can create any number of variables to be used within your templates. You assign values within your PHP code and display the output within your template. This helps separate the logic and presentation layers for cleaner code and maintainability.
Change the Title
Let’s change the title to read Hello World.
Open doc_root/index.php and change the title variable value from:
$smarty->assign('title', 'Welcome smarty pants.');
To:
$smarty->assign('title', 'Hello world.');
Save and view the page again to see your change.
Smarty variables are in the following format:
{$title}
Once you assign your variable in the PHP page you can use the new variable in the assigned template (your .tpl files) anywhere and as many times necessary.
Template Location
All of the templates for the example are located in doc_root/include/smarty/templates. When you call a template to display the path is relative to the setting in config.php.
If you want to add a new template in a sub folder such as about/index.tpl you will need to call the template as follows in your index.php, or new PHP file:
$smarty->display('about/index.tpl');
Download and Demo
View the example in action.
Grab your copy here.























