I’ve been working with PHP frameworks for a while, and I must say, the combination of CodeIgniter and Smarty is absolutely phenomenal. CodeIgniter gives you that lightweight, powerful MVC framework, but it doesn’t come with a built-in template engine. That’s where Smarty steps in and transforms how you handle your views.
Let me walk you through integrating these two powerful tools together. Trust me, once you’ve got this set up, your web development workflow will become so much smoother!
Before diving in, make sure you have:
Don’t worry if you’re not an expert – this guide is designed for beginners to intermediate developers. If you need to brush up on the basics first, check out my other tutorials on CodeIgniter basics and Smarty fundamentals.
Let’s get everything installed and configured properly:
First, grab the latest version of CodeIgniter from their official website. As of 2025, we’re working with CodeIgniter 4.x, which has a slightly different directory structure than earlier versions.
Extract the downloaded files to your local server directory (like htdocs or www).
Next, download the latest Smarty library from smarty.net. The current stable version is 4.x, which includes significant performance improvements over previous versions.
Extract the Smarty files and place the ‘smarty’ directory inside the CodeIgniter’s app/ThirdParty directory (in CodeIgniter 4) or application/third_party directory (in CodeIgniter 3).
Now, we need to create a custom library class that will handle Smarty integration. Create a file named Mysmarty.php in the app/Libraries directory (CI4) or application/libraries directory (CI3).
Here’s the updated MySmarty class for CodeIgniter 4:
<?php
namespace App\Libraries;
class Mysmarty {
private $smarty;
public function __construct() {
// Include Smarty class
require_once APPPATH . 'ThirdParty/smarty/libs/Smarty.class.php';
// Initialize Smarty object
$this->smarty = new \Smarty();
// Set Smarty directories
$this->smarty->setTemplateDir(APPPATH . 'Views/templates/');
$this->smarty->setCompileDir(WRITEPATH . 'smarty/templates_c/');
$this->smarty->setCacheDir(WRITEPATH . 'smarty/cache/');
$this->smarty->setConfigDir(APPPATH . 'Views/templates/configs/');
// Make required directories if they don't exist
if (!is_dir(WRITEPATH . 'smarty/templates_c/')) {
mkdir(WRITEPATH . 'smarty/templates_c/', 0777, true);
}
if (!is_dir(WRITEPATH . 'smarty/cache/')) {
mkdir(WRITEPATH . 'smarty/cache/', 0777, true);
}
// Set caching preferences
$this->smarty->setCaching(\Smarty::CACHING_OFF);
// Additional configurations
$this->smarty->setEscapeHtml(true); <em>// Security feature to automatically escape HTML</em>
}
// Pass-through methods to Smarty
public function assign($key, $value) {
$this->smarty->assign($key, $value);
}
public function display($template) {
$this->smarty->display($template);
}
public function fetch($template) {
return $this->smarty->fetch($template);
}
// Get the underlying Smarty object if needed
public function getSmarty() {
return $this->smarty;
}
}Code language: PHP (php) For CodeIgniter 3 users, here’s the compatible class:
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Mysmarty {
private $CI;
private $smarty;
public function __construct() {
$this->CI =& get_instance();
// Include Smarty class
require_once APPPATH . 'third_party/smarty/libs/Smarty.class.php';
// Initialize Smarty object
$this->smarty = new Smarty();
// Set Smarty directories
$this->smarty->setTemplateDir(APPPATH . 'views/');
$this->smarty->setCompileDir(APPPATH . 'cache/smarty/templates_c/');
$this->smarty->setCacheDir(APPPATH . 'cache/smarty/cache/');
$this->smarty->setConfigDir(APPPATH . 'views/configs/');
// Make required directories if they don't exist
if (!is_dir(APPPATH . 'cache/smarty/templates_c/')) {
mkdir(APPPATH . 'cache/smarty/templates_c/', 0777, true);
}
if (!is_dir(APPPATH . 'cache/smarty/cache/')) {
mkdir(APPPATH . 'cache/smarty/cache/', 0777, true);
}
// Set caching preferences
$this->smarty->setCaching(Smarty::CACHING_OFF);
// Additional configurations
$this->smarty->setEscapeHtml(true);
}
public function assign($key, $value) {
$this->smarty->assign($key, $value);
}
public function display($template) {
$this->smarty->display($template);
}
public function fetch($template) {
return $this->smarty->fetch($template);
}
public function getSmarty() {
return $this->smarty;
}
}Code language: PHP (php) To make our Smarty library available throughout the application, let’s add it to the auto-load configuration:
For CodeIgniter 4, open app/Config/Autoload.php and add:
public $libraries = ['mysmarty'];Code language: PHP (php) For CodeIgniter 3, open application/config/autoload.php and add:
$autoload['libraries'] = array('mysmarty');Code language: PHP (php) Now comes the fun part – actually using Smarty in your controllers! Here’s a simple example of how to use Smarty in a CodeIgniter 4 controller:
<?php namespace App\Controllers;
class Home extends BaseController
{
public function index()
{
// Assign variables to Smarty
$this->mysmarty->assign('title', 'Welcome to CodeIgniter with Smarty!');
$this->mysmarty->assign('description', 'This is an example of using Smarty with CodeIgniter 4');
// Display the template
$this->mysmarty->display('index.tpl');
}
}Code language: HTML, XML (xml) For CodeIgniter 3:
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Home extends CI_Controller {
public function index()
{
// Assign variables to Smarty
$this->mysmarty->assign('title', 'Welcome to CodeIgniter with Smarty!');
$this->mysmarty->assign('description', 'This is an example of using Smarty with CodeIgniter 3');
// Display the template
$this->mysmarty->display('index.tpl');
}
}Code language: HTML, XML (xml) Let’s create a simple Smarty template to display our data. Create a file named index.tpl in your views directory:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>{$title}</title>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css">
</head>
<body>
<div class="container mt-5">
<div class="row">
<div class="col-md-8 offset-md-2">
<div class="card">
<div class="card-header bg-primary text-white">
<h2>{$title}</h2>
</div>
<div class="card-body">
<p class="lead">{$description}</p>
{if isset($items) && count($items) > 0}
<ul class="list-group mt-4">
{foreach $items as $item}
<li class="list-group-item">{$item}</li>
{/foreach}
</ul>
{/if}
</div>
</div>
</div>
</div>
</div>
</body>
</html>Code language: HTML, XML (xml) For better code organization, I strongly recommend creating a base controller that all your other controllers will extend. This allows you to handle common functionality like Smarty template rendering in one place.
For CodeIgniter 4, create app/Controllers/BaseController.php:
<?php namespace App\Controllers;
use CodeIgniter\Controller;
class BaseController extends Controller
{
protected $helpers = [];
public function initController(\CodeIgniter\HTTP\RequestInterface $request, \CodeIgniter\HTTP\ResponseInterface $response, \Psr\Log\LoggerInterface $logger)
{
parent::initController($request, $response, $logger);
}
/**
* Render a Smarty template with provided data
*/
protected function view($template, $data = [])
{
// Assign all data to Smarty variables
if (!empty($data)) {
foreach ($data as $key => $value) {
$this->mysmarty->assign($key, $value);
}
}
// Display the template
$this->mysmarty->display($template . '.tpl');
}
}Code language: HTML, XML (xml) For CodeIgniter 3, create application/core/MY_Controller.php:
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class MY_Controller extends CI_Controller
{
public function __construct()
{
parent::__construct();
}
/**
* Render a Smarty template with provided data
*/
protected function view($template, $data = NULL)
{
// Assign all data to Smarty variables
if ($data != NULL) {
foreach ($data as $key => $value) {
$this->mysmarty->assign($key, $value);
}
}
// Display the template
$this->mysmarty->display($template . '.tpl');
}
}Code language: HTML, XML (xml) If you’re already using CodeIgniter’s built-in views and want to switch to Smarty, the transition is actually quite simple. Here’s how to do it:
$this->load->view("template", $data) with $this->view("template", $data).php to .tplFor example, if you have this code in your controller:
public function about()
{
$data["message"] = "About Smarty And CodeIgniter";
return $this->load->view("about", $data);
}Code language: PHP (php) Simply change it to:
public function about()
{
$data["message"] = "About Smarty And CodeIgniter";
return $this->view("about", $data);
}Code language: PHP (php) And convert your view from:
<!-- PHP/HTML View -->
<h1>About</h1>
<p><?php echo $message; ?></p>Code language: HTML, XML (xml) To:
<!-- Smarty Template -->
<h1>About</h1>
<p>{$message}</p>Code language: HTML, XML (xml) Smarty offers tons of powerful features that can make your templates more dynamic and maintainable:
One of my favorite Smarty features is template inheritance, which works magnificently with CodeIgniter’s structure:
Create a base template layouts/main.tpl:
<!DOCTYPE html>
<html>
<head>
<title>{block name="title"}Default Title{/block}</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="/assets/css/style.css">
{block name="head"}{/block}
</head>
<body>
<header>
<nav>
<ul>
<li><a href="/">Home</a></li>
<li><a href="/about">About</a></li>
<li><a href="/contact">Contact</a></li>
</ul>
</nav>
</header>
<main>
{block name="content"}Default Content{/block}
</main>
<footer>
<p>© {$smarty.now|date_format:"%Y"} My CodeIgniter & Smarty App</p>
</footer>
<script src="/assets/js/main.js"></script>
{block name="scripts"}{/block}
</body>
</html>Code language: HTML, XML (xml) Then extend it in your page templates:
{extends file="layouts/main.tpl"}
{block name="title"}About Us - My Website{/block}
{block name="content"}
<h1>About Us</h1>
<p>{$message}</p>
{/block}
{block name="scripts"}
<script src="/assets/js/about.js"></script>
{/block}Code language: HTML, XML (xml) Smarty allows you to create custom plugins to extend functionality. Here’s a simple example of adding a custom function plugin:
Create a file app/Libraries/Smarty_Plugins/function.current_year.php:
<?php
function smarty_function_current_year($params, $smarty)
{
return date('Y');
}Code language: HTML, XML (xml) Register the plugin in your Mysmarty class:
// In your Mysmarty constructor
$this->smarty->addPluginsDir(APPPATH . 'Libraries/Smarty_Plugins/');Code language: PHP (php) Use it in your templates:
<footer>
<p>© {current_year} My Website</p>
</footer>Code language: HTML, XML (xml) To get the most out of Smarty with CodeIgniter, consider these performance tips:
$this->smarty->setCaching(Smarty::CACHING_LIFETIME_CURRENT);
$this->smarty->setCacheLifetime(3600); <em>// Cache for 1 hour</em>Code language: PHP (php) $this->smarty->setCompileCheck(false);if (ENVIRONMENT === 'production') {
$this->smarty->setCaching(Smarty::CACHING_LIFETIME_CURRENT);
$this->smarty->setCompileCheck(false);
} else {
$this->smarty->setCaching(Smarty::CACHING_OFF);
$this->smarty->setCompileCheck(true);
}Code language: PHP (php) Tip💡: Level up your Codeigniter framework skill with our series of tutorials.
Let’s build a simple dashboard page to demonstrate how powerful the Smarty-CodeIgniter combination can be:
Controller:
public function dashboard()
{
$data = [
'pageTitle' => 'Admin Dashboard',
'username' => 'John Doe',
'stats' => [
'visitors' => 1245,
'sales' => 543,
'revenue' => 12500.75,
'conversion' => 4.3
],
'recentOrders' => [
['id' => 1001, 'customer' => 'Alice Smith', 'amount' => 125.99, 'status' => 'completed'],
['id' => 1002, 'customer' => 'Bob Johnson', 'amount' => 89.50, 'status' => 'processing'],
['id' => 1003, 'customer' => 'Carol White', 'amount' => 210.75, 'status' => 'completed'],
['id' => 1004, 'customer' => 'Dave Brown', 'amount' => 55.25, 'status' => 'pending']
]
];
return $this->view('admin/dashboard', $data);
}Code language: PHP (php) Smarty Template (admin/dashboard.tpl):
{extends file="layouts/admin.tpl"}
{block name="title"}{$pageTitle}{/block}
{block name="content"}
<div class="dashboard-header">
<h1>Welcome back, {$username}!</h1>
<p>Here's what's happening today</p>
</div>
<div class="stats-grid">
<div class="stat-card">
<h3>Visitors</h3>
<div class="stat-value">{$stats.visitors|number_format}</div>
</div>
<div class="stat-card">
<h3>Sales</h3>
<div class="stat-value">{$stats.sales|number_format}</div>
</div>
<div class="stat-card">
<h3>Revenue</h3>
<div class="stat-value">${$stats.revenue|number_format:2}</div>
</div>
<div class="stat-card">
<h3>Conversion</h3>
<div class="stat-value">{$stats.conversion}%</div>
</div>
</div>
<div class="recent-orders">
<h2>Recent Orders</h2>
<table class="table">
<thead>
<tr>
<th>Order ID</th>
<th>Customer</th>
<th>Amount</th>
<th>Status</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
{foreach $recentOrders as $order}
<tr>
<td>#{$order.id}</td>
<td>{$order.customer}</td>
<td>${$order.amount|number_format:2}</td>
<td>
<span class="status-badge status-{$order.status}">
{$order.status|capitalize}
</span>
</td>
<td>
<a href="/admin/orders/{$order.id}" class="btn btn-sm btn-primary">View</a>
</td>
</tr>
{foreachelse}
<tr>
<td colspan="5">No recent orders found</td>
</tr>
{/foreach}
</tbody>
</table>
</div>
{/block}Code language: HTML, XML (xml) After using this integration for years across numerous projects, I can confidently say that Smarty and CodeIgniter form a powerful duo that significantly improves development workflow. Here’s why:
By following this guide, you now have a robust foundation for building complex web applications with a clean, maintainable codebase. The combination of CodeIgniter’s lightweight MVC structure and Smarty’s powerful templating features gives you the best of both worlds.
Have questions about integrating Smarty with CodeIgniter? Hit me up in the comments below, and I’ll help you solve any issues you might encounter!
Happy coding! 🚀
Tired of repetitive tasks eating up your time? Python can help you automate the boring stuff — from organizing files to scraping websites and sending…
Learn python file handling from scratch! This comprehensive guide walks you through reading, writing, and managing files in Python with real-world examples, troubleshooting tips, and…
You've conquered the service worker lifecycle, mastered caching strategies, and explored advanced features. Now it's time to lock down your implementation with battle-tested service worker…
This website uses cookies.
View Comments
very nice ... going to implement it now ... will see if any issues...thank you,
How can i include header.php/tpl and footer pages dynamically without creating assoc array? please suggest