Smarty Template Engine: How to install and use? [BEGINNER’S GUIDE]

In this article, I will be introducing how to use Smarty Template engine. This is a beginner tutorial.

First of all, you need to download Smarty from http://www.smarty.net/download. You can follow a quickstart guide from here as well: http://www.smarty.net/quick_install. My approach of coding is a bit different than the quickstart guide present on smarty website.

First, you download the latest version of Smarty; extract it and put it on your website. So, your Smarty path will be like: http://example.com/smarty/

I have the following files and directory structure:


- index.php
- classes
    ---- ConnectSmarty.class.php
- smarty_temp
    ----- templates
        ----- ---- index.tpl
    ----- templates_c
    ----- cache
    ----- configs
- smarty/... (main smarty folder)

ConnectSmarty.class.php defines the different temp directories.


<?php
/**
 * Full path of smarty
 */
require_once 'smarty/libs/Smarty.class.php';

/**
 * Connection to Smarty package
 * 
 */

class ConnectSmarty extends Smarty 
{
	/** 
	* Defile paths to smarty directories
	* 
	* @access public
	*/		
	public function __construct()
	{		    
		parent::__construct();

		// set default dirs
		$this->setTemplateDir('smarty_temp/templates')
			->setCompileDir('smarty_temp/templates_c')            
			->setCacheDir('smarty_temp/cache')
			->setConfigDir('smarty_temp/configs');
	}
}
?>

index.php assigns content and calls index.tpl file.


<?php
require_once('classes/ConnectSmarty.class.php');

// create an object of the class included above
$smarty = new ConnectSmarty;

// assign content
$smarty->assign('name','Mukesh Chapagain');
$smarty->assign('address','Kathmandu, Nepal');

// display the content
$smarty->display('index.tpl');
?>

index.tpl displays the content as assigned by index.php.


<html>
<head>
<title> Homepage </title>
</head>
<body>
The author of this tutorial:<br/><br/>
Name: {$name} <br/>
Address: {$address} <br/>
</body>
</html>

Hope it helps.
Thanks.