Getting started with Smarty templating

A few days ago I started using smarty. I was amazed by what you can do with this templating engine. Smarty is a templating engine written in php which allows you to easily split the PHP code from your html code. The smarty developers call it a “Template/Presentation Framework” because it‘s not just a tag replacing template engine. Templating is especially useful when you work with web designers who have little or no knowledge of PHP. They can easily change the html code in the tpl files without being bombarded with PHP code. I am a web developer and I started using a templating class which just enabled me to assign variables and blocks. I now use smarty for my CMS. It took me about 2,5 days to implement it because the templating class I used, worked completely different from Smarty. Smarty enables me to loop through arrays, use modifiers (which are basically custom PHP functions that work within smarty), cache files, debugging and so much more.  Some of the main features of smarty are:

getting started:

At first I was confronted with a couple of problems. It took me quite a while before I figured out what I was doing wrong. First of all you need to copy the libs folder in your project. Then you need to include the smarty class in your php file. You could also include this path in your php.ini file if you have access to it, which I don‘t so I use the following code for this. Place this at the top of your php file:

require("../libs/Smarty.class.php");

$smarty = new Smarty;
$smarty->template_dir '../templates/';
$smarty->compile_dir  '../templates_c/';
$smarty->config_dir   '../configs/';
$smarty->cache_dir    '../cache/';

Then make 4 folders:

Chmod these folders 700. Change the cache_dir, config_dir, template_dir and compile_dir to the location where these folders reside. If your php file is e.g. index.php make a file index.tpl in the templates folder. 

Then add this code to the bottom of your php file:

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

the default folder for your templates is templates so leave out the folder in the path. 

To assign a variable in the php file:

$var =" This is a piece of text";

$smarty->assign("VARIABLE", $var);

Call the variable in your template file like this:

{ $VARIABLE}

you can change the left deilimter’{’ and right delimiter ’}’ in the smarty.class.php file by changing the variables: $left_delimiter and $right_delimiter.

As I said, I faced a couple of problems using smarty.  First problem I encountered was with inline javascript. Apparently smarty gets confused with curly braces used in inline javascript so you have to place your javascript within these tags: { literal } and { /literal }. That way Smarty knows he doesn‘t have to search for variables in this block. You can also use the { ldelim } and { rdelim }  tags to specify the left curly brace and right curly brace in your code. The next problem was a caching problem. In my CMS I use multiple index.php files so smarty, with caching enabled, often presented me the wrong page. I had to set caching to false in the Smarty config file, located in the libs folder. Furthermore I noticed that smarty has some issues with get variables. Some characters aren‘t allowed apparently.


Commonly used Smarty modifiers

string format

{ $number|string_format:'%2f' } results in e.g. 2.45

{ $number|string_format:'%d' } results in e.g. 2

date_format

{ $date|date_format:'%Y/%m/%d } result in e.g. 2009/04/30

mailto

to avoid spam indexers you should use the mailto function to encode an email address

{ mailto address=$email encode=‘javascript subject=‘email test’ }

cycle

The cycle function enables you to cycle through a list of predefined list of values. E.g. alternating colors for tables:

< tr style="background-color:{ cycle values="#f3f3f3, #dddd } ">

strip

The strip tag removes extra whitespace before and after a piece of text. e.g.:

{ strip }> 
$text 
{ /strip }

truncate

A bit like the substring function but with the ability to cut off after the last word.

{ $text|trunctate:30:'...':true }

the 30 indicates the amount of characters allowed and the true indicates it can only cut off after the last word.

substr

As I said the substr is a bit more limited 

{ $text|substr:30 }

indent

the indent function indents pieces of text. e.g.:

{ $text|indent:10:'-' } -> indents the text with 10 hyphens

replace

this functions replaces characters within a string

{ $text|replace:'cats':'dogs' } -> replaces the word 'cats' with 'dogs'

default

Allow you to set a default value when no value is given

{ $text|default:'First title } -> If the $text variable is empty the 'First title' will be used

print_r

Equivalent to the PHP print_r function. usage:

{ $text|@print_r }

Other modifiers

the following functions are pretty self-explanatory:

{ $text|upper } -> puts text in uppercase

{ $text|html_entity_decode } -> the html_entity_decode php function

{ $text|capitalize } -> capitalizes the first letter

{ $text|count_characters } -> the amount of characters in the $text variable

{ $text|count_paragraphs } -> the amount of paragraphs in the $text variable

{ $text|count_words } -> the amount of words in the $text variable

{ $text|count_sentences } -> the amount of sentences in the $text variable

PHP_SELF

{ $smarty.server.PHP_SELF} return the current page. 

How to combine modifiers

It‘s very easy to combine these modifiers by adding a pipe sign in between them. Like so:

{ $text|html_entity_decode|truncate:30:true|default:'No title' }

Form - related functions

checkboxes

I‘ll use an example for this:

PHP file:

$smarty->assign('types', array( 

'first' => 'first type', 

'second' => 'second type', 

)); 

TPL file:

{ html_checkboxes name="type" options=$types separator="< br / >" }

 

This would generate 2 checkboxes.

Radio buttons

Same way for radio buttons

{ html_radios name="type" options=$types selected="first"}

Dropdowns

< select name="actief" size="">
  { html_options options=$provincies selected=0 }
< /select>

Date and time dropdowns

{ html_select_date display_years=false } 
{ html_select_time display_seconds=false minute_interval=15 } 

The first functions generates two dropdowns for the day and month. Leave out the display_years=false to add a year dropdown. The second function also generates two dropdowns with the hours and minutes with an interval of 15 minutes, otherwise it would be a long dropdown with 60 values.

I also wrote another post on how to use multiple language support for Smarty.

Comments

Posted on 13-06 by Jehnee

thanks for your wonderful tutorial it's hard to find like this smarty tuts.

Posted on 16-12 by Opomulero

Great Tut!

Leave a comment