If you’re a PHP developer looking to separate your business logic from presentation, Smarty is absolutely the template engine you need in your toolkit. I’ve been using Smarty for years, and I constantly find myself referring back to certain techniques and tricks that make development faster and more efficient.
This guide compiles the most essential PHP Smarty examples and tips I use almost daily. Trust me – these will save you hours of development time and make your code significantly cleaner!
Note: if you are completely new to PHP Smarty, highly recommend to check out this beginners guide to PHP Smarty Template Engine first.
One of the most powerful features of Smarty is how seamlessly it lets you integrate PHP functionality into your templates. Here are the most effective ways to do this:
You can directly use PHP functions inside Smarty’s conditional statements without any special syntax:
{if strstr($string1, $string2)}
String match found!
{/if}
{if empty($array)}
No data available
{/if}
Code language: PHP (php)
Smarty lets you apply PHP functions as variable modifiers using the pipe (|) symbol. This approach is incredibly versatile:
{* Using count() on an array *}
We have {$smarty_array_variable|count} entries in our record.
{* For functions with multiple parameters, the variable is passed as the first parameter *}
{$long_string|strstr:"search_term"}
Code language: PHP (php)
Note: In Smarty 3.x, the {php}
tag has been deprecated. While it worked in Smarty 2.x, using it in modern templates is discouraged as it breaks the separation of concerns that makes Smarty valuable in the first place.
A common source of confusion for Smarty beginners is when to use foreach
versus section
. Here’s my definitive guide:
In most scenarios, foreach
is your go-to looping construct. It’s easier to read, more intuitive, and recommended by the Smarty team. Always use foreach
when:
Example:
{foreach $users as $user}
Name: {$user.name} | Email: {$user.email}
{/foreach}
Code language: PHP (php)
The section
construct has some specialized use cases where it shines:
Example:
{section name=customer loop=$customers}
{if $smarty.section.customer.index is even}
<div class="even-row">
{else}
<div class="odd-row">
{/if}
Customer: {$customers[customer]}
Location: {$locations[customer]}
</div>
{/section}
Code language: HTML, XML (xml)
Incrementing variables might seem basic, but it’s tremendously useful in templates. Here’s how to do it:
{* Method 1: Direct assignment *}
{assign var=counter value=1}
{assign var=counter value=$counter+1}
{* Method 2: Using capture for more complex operations *}
{assign var=counter value=1}
{capture assign=counter}{$counter+1}{/capture}
{* Output: 2 *}
The counter value is: {$counter}
Code language: PHP (php)
Performance is critical for modern web applications. Smarty’s caching capabilities can dramatically speed up your site:
// Set cache lifetime to 5 minutes (300 seconds)
$smarty->setCaching(Smarty::CACHING_LIFETIME_CURRENT);
$smarty->setCacheLifetime(300);
// Clear all available cache
$smarty->clearAllCache();
// Check if a cached version exists
if ($smarty->isCached('template.tpl')) {
// Use cached version
}
Code language: PHP (php)
To exclude specific sections from caching (like user-specific content), wrap them with the {nocache}
tag:
{* This will be cached *}
<div class="static-content">
Static content here
</div>
{* This will never be cached *}
{nocache}
<div class="user-specific">
Welcome, {$user.name}!
Current time: {$smarty.now|date_format:"%H:%M:%S"}
</div>
{/nocache}
Code language: HTML, XML (xml)
Smarty uses curly braces {
and }
for its syntax, which can clash with JavaScript. The fix is remarkably simple – use the {literal}
tag:
{literal}
<script>
function toggleVisibility() {
let element = document.getElementById('content');
if (element.style.display === 'none') {
element.style.display = 'block';
} else {
element.style.display = 'none';
}
}
</script>
{/literal}
Code language: HTML, XML (xml)
For hybrid scenarios where you need both JavaScript and Smarty variables, use this technique:
<script>
{literal}
function greetUser(name) {
alert('Hello, ' + name + '!');
}
{/literal}
// Call the function with a Smarty variable
document.addEventListener('DOMContentLoaded', function() {
greetUser('{$user.name}');
});
</script>
Code language: HTML, XML (xml)
Create your own template modifiers to extend Smarty’s functionality:
// In your PHP setup code
$smarty->registerPlugin('modifier', 'truncate_and_ellipsis', 'myTruncateFunction');
function myTruncateFunction($string, $length = 50) {
if (strlen($string) > $length) {
return substr($string, 0, $length) . '...';
}
return $string;
}
Code language: PHP (php)
Then use it in your template:
{$long_description|truncate_and_ellipsis:100}
Code language: PHP (php)
Modern web applications frequently exchange JSON data. Smarty makes this easy:
{* Convert PHP array to JSON *}
<script>
const userData = {$user_data|json_encode};
</script>
{* Parse JSON string back to Smarty variable *}
{assign var=parsed_data value=$json_string|json_decode:true}
Code language: PHP (php)
When things aren’t working as expected, Smarty’s built-in debugging is invaluable:
// Enable debug output
$smarty->debugging = true;
// Or for specific templates only
$smarty->debugging_ctrl = 'URL';
// Then append ?SMARTY_DEBUG to your URL
Code language: PHP (php)
Solution: Verify the variable was assigned properly. Use {$smarty.capture.default}
to see all output.
Solution: Check for unclosed tags or mismatched delimiters. Use $smarty->muteExpectedErrors()
during development.
Solution: Enable caching, compile check only in development, and use {include}
sparingly.
These PHP Smarty examples cover the most practical techniques you’ll use daily. The template engine becomes exponentially more powerful once you master these concepts.
For beginners, focus on mastering variable modifiers and foreach loops first. Intermediate developers should experiment with caching and custom plugins to extend functionality.
I’ll be updating this guide with more advanced techniques as I continue working with Smarty. Have questions or your own tips to share? Drop a comment below!
Q: How do I increment a page view counter in Smarty?
A: You’ll need to handle this in your PHP controller, then display it in Smarty:
// In your controller
$viewCount = getCurrentViewCount(); // Get from database
$viewCount++;
updateViewCount($viewCount); // Update database
$smarty->assign('view_count', $viewCount);
Code language: PHP (php)
{* In your template *}
This page has been viewed {$view_count} times.
Code language: PHP (php)
Q: Can Smarty handle file uploads?
A: Smarty is a template engine, so file uploads should be handled in your PHP code, but you can display upload forms and results with Smarty.
Q: Is Smarty still relevant with modern PHP frameworks?
A: Absolutely! While many frameworks have their own templating systems, Smarty’s powerful features and mature ecosystem make it a valuable option, especially for complex templating needs.
Unlock the full potential of service workers with advanced features like push notifications, background sync, and performance optimization techniques that transform your web app into…
Learn how to integrate service workers in React, Next.js, Vue, and Angular with practical code examples and production-ready implementations for modern web applications.
Master the essential service worker caching strategies that transform web performance. Learn Cache-First, Network-First, and Stale-While-Revalidate patterns with practical examples that'll make your apps blazingly…
This website uses cookies.
View Comments
thank u for your explanations. how to code in smarty when i wanna increment page view count +1 whenever the page is loaded and the incremented value is updated to mysql database, how to code that in php mysql and smarty tpl? would u help me to code this? thanks in advance