Swiftorial Logo
Home
Swift Lessons
Matchups
CodeSnaps
Tutorials
Career
Resources

Using Smarty - Comprehensive Tutorial

Introduction

Smarty is a template engine for PHP, facilitating the separation of presentation (HTML/CSS) from application logic (PHP). This tutorial will guide you through the process of using Smarty from start to finish, with detailed explanations and examples.

Installation

To start using Smarty, you need to install it. You can do this using Composer:

composer require smarty/smarty

Once installed, you can include it in your project:

require 'vendor/autoload.php';

Basic Setup

To initialize Smarty, you need to create an instance of the Smarty class and configure a few directories:

$smarty = new Smarty();
$smarty->setTemplateDir('path/to/templates');
$smarty->setCompileDir('path/to/templates_c');
$smarty->setCacheDir('path/to/cache');
$smarty->setConfigDir('path/to/configs');

Creating Templates

Smarty templates are simple HTML files with embedded Smarty tags. Here's an example of a basic template:

<!DOCTYPE html>
<html>
<head>
<title>{$title}</title>
</head>
<body>
<h1>{$heading}</h1>
<p>{$content}</p>
</body>
</html>

Assigning Variables

To pass data from your PHP script to your Smarty template, you use the assign method:

$smarty->assign('title', 'Welcome to Smarty');
$smarty->assign('heading', 'Hello, World!');
$smarty->assign('content', 'This is a sample page using Smarty.');

Now, you can display your template:

$smarty->display('example.tpl');

Using Loops

Smarty supports loops, which are useful for displaying data from arrays. Here's an example:

<ul>
{foreach from=$items item=item}
<li>{$item}</li>
{/foreach}
</ul>

Assign an array in your PHP script:

$items = array('Item 1', 'Item 2', 'Item 3');
$smarty->assign('items', $items);

Using Conditionals

Smarty also supports conditional statements. Here's an example:

{if $user_logged_in}
<p>Welcome, {$username}!</p>
{else}
<p>Please log in.</p>
{/if}

Assign variables in your PHP script:

$smarty->assign('user_logged_in', true);
$smarty->assign('username', 'JohnDoe');

Including Templates

Smarty allows you to include other templates within a template, making it easy to reuse components. Here's an example:

<!-- main.tpl -->
<html>
<head></head>
<body>
{include file='header.tpl'}
<h1>Main Content</h1>
{include file='footer.tpl'}
</body>
</html>

Conclusion

Smarty is a powerful and flexible templating engine for PHP. By separating your presentation logic from your application logic, Smarty helps you create cleaner, more maintainable code. This tutorial covered the basics, but there's much more you can do with Smarty. Be sure to check out the official Smarty documentation for more advanced features.