Introduction To The Smarty Templating Framework
Introduction To The Smarty Templating Framework
Introduction To The Smarty Templating Framework
Smarty is a PHP-based templating engine/framework. It allows you to further separate your business logic from its visualization, by
removing as much PHP code as possible away from your views. Some developers and frameworks prefer not to use a templating
engine, others do prefer them to using plain PHP in your views. Both points of view can be argued, and in the end, it's mostly a matter
of taste. Anyway, it's never a bad idea to try it out before deciding not to use it, and that's what this tutorial is about: trying out the
Smarty Templating Framework.
Before you're able to use something, you have to install it. Thankfully, installing Smarty is extremely easy and requires almost no
con guration. First of all, download Smarty and extract the archive. You can check out everything inside the archive, but we'll only
need the "libs" folder for our application. Rename it to "smarty" and paste it inside the "lib" folder of our application. Smarty uses some
additional folders, so create the "templates_c", "cache" and "con gs" folders inside our "lib/smarty" folder. If you're not using Windows,
you'll have to give 775 permissions on these folders to your webserver. Your directory tree should now look like this:
Every programmer has his own idea about the ideal API. In order to adjust Smarty's API slightly, and allow us to add some additional
functionality, we'll create a wrapper class called SMTemplate, which will take care of the smarty details for us. This approach has
another advantage: if, at one moment in time, you should choose to use another template engine, you can create a wrapper for that
engine, while retaining the SMTemplate interface, and thus without breaking the code that uses our SMTemplate class.
01 /**
02 * @file
03 * Configuration file for the SMTemplate class
04 */
05
06 $smtemplate_config =
07 array(
08 'template_dir' => 'views/',
09 'compile_dir' => 'lib/smarty/templates_c/',
10 'cache_dir' => 'lib/smarty/cache/',
11 'configs_dir' => 'lib/smarty/configs/',
12 );
01 /**
02 * @file
03 * Wrapper for Smarty Template Engine
04 */
05
06 require_once('smarty/Smarty.class.php');
07 require_once('smtemplate_config.php');
08
09 class SMTemplate{
10
11 private $_smarty;
12
13 function __construct(){
14 $this->_smarty = new Smarty();
15
16 global $smtemplate_config;
17 $this->_smarty->template_dir = $smtemplate_config['template_dir'];
18 $this->_smarty->compile_dir = $smtemplate_config['compile_dir'];
19 $this->_smarty->cache_dir = $smtemplate_config['cache_dir'];
20 $this->_smarty->configs_dir = $smtemplate_config['configs_dir'];
21 }
22 }
Rendering templates
As you can see, our class is still pretty pathetic, as it can't render anything. We'll solve this issue by adding a render function, which
loads a template and displays it.
1 function render($template){
2 $this->_smarty->display($template . '.tpl');
3 }
In order to render anything, we'll need to create a template le, and then call the render function from our index.php le. The template
le will be pretty basic containing a simple html page Name it "home tpl" and place it inside our "views" directory
https://code.tutsplus.com/tutorials/introduction-to-the-smarty-templating-framework--net-14408 2/17
11/9/2017 Introduction to the Smarty Templating Framework
le will be pretty basic, containing a simple html page. Name it home.tpl , and place it inside our views directory.
01 <html>
02 <head>
03 <meta http-equiv="Content-type" content="text/html; charset=utf-8" />
04 <title>Home</title>
05 <link rel="stylesheet" href="/css/master.css" type="text/css" media="screen" title="no title" charset="utf-8" />
06 </head>
07 <body>
08 <p>Hello, World!</p>
09 </body>
10 </html>
Now, all that is left is to create an SMTemplate object and render 'home'. Open up index.php, add the following lines of code, and
navigate there in your browser.
1 require_once('lib/smtemplate.php');
2
3 $tpl = new SMTemplate();
4 $tpl->render('home');
1 <body>
2 <p>Hello, {$receiver}! It's {$date} today!</p>
3 </body>
If you refresh the page, you'll see that the variables haven't been lled in, since we didn't set them. Setting variables can be done using
smarty->assign, so let's assign them. The render function will now take an optional data array as a second argument.
It still won't work, because we don't pass in an array when calling our render function. We can easily do this, by altering a few lines in
our index.php le.
1 $data = array(
2 'receiver' => 'JR',
3 'date' => time(),
4 );
5
6 $tpl = new SMTemplate();
7 $tpl->render('home', $data);
If you refresh now, the page will say something like "Hello, JR! It's 1282810169 today!". Of course, this date isn't really what we had in
mind. It needs to be formatted, which brings us to the next section.
1 <body>
2 <p>Hello, {$receiver}! It's {$date|date_format:"%d %B"} today!</p>
3 </body>
This should now give something of the form "Hello, JR! It's 26 August today!" Now, maybe we want to make sure our receiver is
uppercased. We can achieve that by using the upper modi er.
1 <body>
2 <p>Hello, {$receiver|upper}! It's {$date|date_format:"%d %B"} today!</p>
3 </body>
Now, if I alter index.php to pass 'jr' instead of 'JR', the template will still show 'JR'. Easy, isn't it? Next, we'll include our templates in a
default "layout".
01 <html>
02 <head>
03 <meta http-equiv="Content-type" content="text/html; charset=utf-8" />
04 <title>Home</title>
05 <link rel="stylesheet" href="/css/master.css" type="text/css" media="screen" title="no title" charset="utf-8" />
06 </head>
07 <body>
08 <hr />
09 <hr />
10 </body>
11 </html>
Of course, this won't cut it, since Smarty won't know where to insert our content. There is more than one way to get content from
another template inside of our layout and I'll use Smarty's fetch function This function returns our template as text instead of
https://code.tutsplus.com/tutorials/introduction-to-the-smarty-templating-framework--net-14408 4/17
11/9/2017 Introduction to the Smarty Templating Framework
another template inside of our layout, and I ll use Smarty s fetch function. This function returns our template as text, instead of
displaying it. This means we can fetch the template, and then assign it to a variable for use within our template! This variable's name
is yours to choose. I pre x my special variables with __, to distinguish them from the other variables I use. I'll call this one 'content',
since we're assigning our page content to it.
1 <body>
2 <hr />
3 {$__content}
4 <hr />
5 </body>
This concludes our layout, so let's create some templates to use as content. I'll create a 'hello' template, which will contain a standard
'hello world' line, and a 'lipsum' template, which holds some Lorem Ipsum text. Don't forget to give these templates a .tpl extension.
1 <p>Hello, World!</p>
1 <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aenean aliquet dignissim diam at vulputate. Aenean nec ligula a
Adapting our SMTemplate class to use a layout is also extremely easy. We'll rst set up a con guration option for the layouts
directory, like we did for our views.
01 /**
02 * @file
03 * Configuration file for the SMTemplate class
04 */
05
06 $smtemplate_config =
07 array(
08 'layouts_dir' => 'layouts/',
09 'template_dir' => 'views/',
10 'compile_dir' => 'lib/smarty/templates_c/',
11 'cache_dir' => 'lib/smarty/cache/',
12 'configs_dir' => 'lib/smarty/configs/',
13 );
Next, we'll change our render function. We'll supply the layout as an optional third parameter, and let it default to 'page'. Then, we'll
fetch the requested template, assign it to the $__content variable, and display our layout.
There are a couple of things to consider, regarding this code. First of all, we haven't told Smarty where to nd our layouts yet. We can
do that by adding a template dir, but this approach means we can't give our layouts the same name as our templates - Smarty
wouldn't know which one to pick. We could solve this by giving our layouts a different extension, or by setting and resetting our
template directory inside our render function, or by using more advanced Smarty functions. For now, we'll just settle with the
constraint that layouts and views can't have the same name. We can add our layouts directory using the addTemplateDir() function.
01 function __construct(){
02 $this->_smarty = new Smarty();
03
04 global $smtemplate_config;
05 $this->_smarty->template_dir = $smtemplate_config['template_dir'];
06 $this->_smarty->addTemplateDir($smtemplate_config['layouts_dir']); // <- new line
07 $this->_smarty->compile_dir = $smtemplate_config['compile_dir'];
08 $this->_smarty->cache_dir = $smtemplate_config['cache_dir'];
09 $this->_smarty->configs_dir = $smtemplate_config['configs_dir'];
10 }
https://code.tutsplus.com/tutorials/introduction-to-the-smarty-templating-framework--net-14408 5/17
11/9/2017 Introduction to the Smarty Templating Framework
10 }
1 require_once('lib/smtemplate.php');
2
3 $tpl = new SMTemplate();
4 $tpl->render('hello');
It works!
1 {$date|date_format:"%d %B"}
If you want a custom modifier, all you need to do is write a PHP function.
This will actually result in a call to the function smarty_modi er_date_format(), with $date and our format string as arguments. This
function will return a string, and this string will be displayed. So if you want a custom modi er, all you need to do is write a PHP
function. As an example, we'll write a modi er called 'weirdcase', which will uppercase all consonants and lowercase all vowels, i.e.
'Lorem Ipsum' becomes 'LoReM IPSuM'. To do this, create a le called 'modi er.weirdcase.php' in the 'lib/smarty/plugins' folder. Our
modi er will take only one argument, the string that needs to be altered.
01 /**
02 * Smarty weirdcase modifier plugin
03 *
04 * Type: modifier
05 * Name: weirdcase
06 * Purpose: turn consonants into uppercase and vowels into lowercase
07 * @param string
08 * @return string
09 */
10
11 function smarty_modifier_weirdcase($string){
12
13
}
https://code.tutsplus.com/tutorials/introduction-to-the-smarty-templating-framework--net-14408 6/17
11/9/2017 Introduction to the Smarty Templating Framework
We can get our result by de ning an array 'vowels', turning our string into an array and then traversing it, and checking whether each
character is in our vowels array. If it is, we lowercase it, otherwise, we uppercase it. The modi ed characters are then appended to a
result variable.
01 function smarty_modifier_weirdcase($string){
02 $str_array = str_split($string);
03 $result = '';
04 $vowels = array('a', 'e', 'i', 'o', 'u');
05
06 foreach ($str_array as $char){
07 if (in_array($vowels, $char)) $result .= strtolower($char);
08 else $result .= strtoupper($char);
09 }
10
11 return $result;
12 }
This should do the trick, so let's check it out. Edit the 'lipsum.tpl' template and add an h1 containing our weirdcased 'Lorem Ipsum' to
it.
1 <h1>{'Lorem Ipsum'|weirdcase}</h1>
2 <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aenean aliquet dignissim diam at vulputate. Aenean nec ligula a
Step 6: Conclusion
Although there is a lot more to Smarty than I could t within this tutorial, hopefully this should provide you with a basic knowledge of
how to work with it. You essentially already know everything you need to know. You should also be able to determine whether you like
the idea of using this templating framework or not by now. The more advanced topics, such as lters and blocks, are useful, however,
you'll still do ne without them. You can nd documentation on the more advanced features at the Smarty website. Thanks for
reading!
Joeri Rammelaere
I'm a 19 year old Computer Science student at the University of Antwerp, with a broad knowledge of programming language. My main
experience is with the C++ and Oberon-2 languages, though I also know other languages, such as Ruby and Haskell. I'm also very
interested in both webdesign and webdevelopment.
https://code.tutsplus.com/tutorials/introduction-to-the-smarty-templating-framework--net-14408 7/17
11/9/2017 Introduction to the Smarty Templating Framework
in_array($char,$vowels);
instead of
in_array($vowels,$char);
2.in Building the SMTemplate Class section we should use proper methods for setting smarty variables
$this->_smarty->setTemplateDir($smtemplate_config['template_dir']);
$this->_smarty->setCompileDir($smtemplate_config['compile_dir']);
$this->_smarty->addTemplateDir($smtemplate_config['layouts_dir']);
$this->_smarty->setCacheDir($smtemplate_config['cache_dir']);
$this->_smarty->setConfigDir($smtemplate_config['configs_dir']);
Great Post
regards,
minakolta
5△ ▽ • Reply • Share ›
Very good tuto, wonder, you could share the code with us on some server ..?
Thanks in advance.
2△ ▽ • Reply • Share ›
Thanks
△ ▽ • Reply • Share ›
https://code.tutsplus.com/tutorials/introduction-to-the-smarty-templating-framework--net-14408 8/17
11/9/2017 Introduction to the Smarty Templating Framework
Md. Zubaer Ahammed • 2 years ago
Great tutorial. But it should be $config_dir rather than $configs_dir. $configs_dir isn't defined in Smarty.class.php, So it will give Undefined property:
Smarty::$configs_dir error if you use $configs_dir. Except this everything is cool.
△ ▽ • Reply • Share ›
△ ▽ • Reply • Share ›
http://onlinewebapplication...
△ ▽ • Reply • Share ›
function render($template){
$this->_smarty->display($template . '.tpl');
}
require_once('smarty/Smarty.class.php');
require_once('smtemplate_config.php');
class SMTemplate{
private $_smarty;
function __construct(){
$this->_smarty = new Smarty();
global $smtemplate_config;
$this->_smarty->template_dir = $smtemplate_config['template_dir'];
$this->_smarty->compile_dir = $smtemplate_config['compile_dir'];
$this->_smarty->cache_dir = $smtemplate_config['cache_dir'];
$this->_smarty->configs_dir = $smtemplate_config['configs_dir'];
}
}
in the smtemplate.php file?
△ ▽ • Reply • Share ›
https://code.tutsplus.com/tutorials/introduction-to-the-smarty-templating-framework--net-14408 10/17
11/9/2017 Introduction to the Smarty Templating Framework
and I have no idea why some peoples still use smarty template for codeigniter --"
△ ▽ • Reply • Share ›
I use smarty to create HTML and PDF documents - yes, PDF, with my own meta language processor! A good way to separate PDF document
formatting from code.
To everyone who thinks smarty is a performance killer: Your "compiled" template will be just executed (included) PHP code - nothing else.
{$blah|escape}
or
You can create your own modifiers, e.g. for escaping to UTF-8. With your own functions and modifiers you can also easily create a "higher" level of
HTML / web application design.
△ ▽ • Reply • Share ›
<strong>{$blah|escape}</strong>
or
https://code.tutsplus.com/tutorials/introduction-to-the-smarty-templating-framework--net-14408 11/17
11/9/2017 Introduction to the Smarty Templating Framework
But I don't see any advantage to create and use SMTemplate class on this way. If you ever want to migrate to some other template system, you will
have other, much greater problems.
△ ▽ • Reply • Share ›
As a templating engine it's one of the clearest but I'm with the others here who try to avoid adding that extra un-necessary layer of code whenever
possible.
△ ▽ • Reply • Share ›
Im looking forward to see whats changed in version 3! Im sure this will be a great tutorial :)
△ ▽ • Reply • Share ›
It was awful. But I get the point with Smarty. It's just not my thing, because I write my own {tag} parser or use CodeIgniter's, which is great!
https://code.tutsplus.com/tutorials/introduction-to-the-smarty-templating-framework--net-14408 13/17
11/9/2017 Introduction to the Smarty Templating Framework
△ ▽ • Reply • Share ›
But still, I like this tutorial as it gives me an inside look to Smarty without me having to learn it.
△ ▽ • Reply • Share ›
i stopped using smarty when they started supporting chained method calling from objects
△ ▽ • Reply • Share ›
Really interesting Article though, I was using Smarty before a year ago, but i avoid using it, as it costs Slowing down my site a little bit, some of my
clients told me that it causes this problem so i refused to use it.
so its good not to use, better use inbuilt templating serviced provided by good frameworks like codeignator, symfony, magento etc etc.
Thanks,
Vijay Padhariya
△ ▽ • Reply • Share ›
nettuts provide us a great tutorial, if we like it or not.... long live nettuts.... the best.
△ ▽ • Reply • Share ›
DJ • 7 years ago
https://code.tutsplus.com/tutorials/introduction-to-the-smarty-templating-framework--net-14408 14/17
11/9/2017 Introduction to the Smarty Templating Framework
You know, as long as we are 'just trying it out' before we decide whether to like it or not, as well written as this is, it would make a great screencast so
we could actually see it work from someone who had already gone to the trouble of downloading and installing it before we decided whether or not to
invest in the effort and band-width. There are some things better seen than explained, this may be one of them. How about making this a screencast?
△ ▽ • Reply • Share ›
And, any reason you went off and made your own class object, rather than extending the Smarty class object with your added functionality?
△ ▽ • Reply • Share ›
You just have to be disciplined enough to strictly divide your business logic and views.
△ ▽ • Reply • Share ›
I do a lot of work with CS-Cart at work which makes use of Smarty. I sometimes find myself guessing when modifying the code so hopefully going over
this thoroughly will help save me some frustration :P
△ ▽ • Reply • Share ›
I'm using smarty3 for my projects now and do it almost exactly as this excellent article suggests (nettuts has risen in quality by the way!).
△ ▽ • Reply • Share ›
By using smarty you give away the ability to do things in straight up PHP, requires you to learn yet another syntax for doing simple things
like if statements, and the reason why they have template cache is because Smarty is slow compared to straight up PHP.
I think it's an abstraction that is too confusing for beginners, and in practice I don't see any massive added benefit from using it. A better
guideline would be "set up all your variables, get stuff out of the database, figure out access and stuff in one script, then require another
php script that is mostly html and makes use of these plain old variables".
That way you get the separation of concerns (fetching data, checking access versus putting it all together in HTML), without the
overhead of yet-another-library that is slower and doesn't give you any extra functionality!
All you need in my opinion is something like PHP ADO and a couple of guidelines like I've mentioned above and you can write easy to
understand code.
△ ▽ • Reply • Share ›
https://code.tutsplus.com/tutorials/introduction-to-the-smarty-templating-framework--net-14408 16/17
11/9/2017 Introduction to the Smarty Templating Framework
https://code.tutsplus.com/tutorials/introduction-to-the-smarty-templating-framework--net-14408 17/17