A Quick Guide to Smarty for Template Writers

By Thomas Davidson
Last updated 6/30/2009
Smarty is a convenient way to divide the work of creating a website into two separate roles: the visuals and the back-end. One person specializing in HTML and CSS can code templates with no knowledge of PHP, while another person can focus entirely on the PHP code driving the site and not worry about layout or the styling of elements on the page.
Your role: As a template writer, you will mostly be writing normal HTML, CSS and Javascript. In fact, any plain HTML page is already a valid Smarty template; it just won’t have anything dynamic. Wherever there’s a title, number, image, or any other feature that can change you’ll need to insert special Smarty tags. Think about what can change on the page. Does a login form disappear once the user logs in? Do new things appear? Do you have a list of recent items, or next/previous links that will depend on what page you’re currently on? There are essentially three types of dynamic information that you might have to act on: Directly-inserted variables, variables used for decisions about what to show, and lists. Please read these in order, since each builds off the one before.
Directly-inserted variables Firstly, there is information that can be directly inserted – for example, a user’s name. You might want the page to say “Welcome, Linda!” or “Welcome, Bob!”, or whatever the user’s first name is. You can’t think of all the possible names in advance, so you’ll need the name to be provided to you. This is passed into your template through a variable. If we call that variable $first_name, you can insert it into your HTML code with the following tag: {$first_name} The PHP coder will deal with how to get that name and how to send it to your template, but all you need to do is insert that simple tag. Please note that ALL variable names must start with a dollar sign, and can only contain letters, numbers, and underscores (no spaces). You may have many pieces of information like this you need to insert, and you should come up with meaningful names for each of them. You may want to discuss them with the PHP coder and come to an agreement on what to call each variable. Variables used for decisions about what to show Let’s say you want to show a menu only to logged-in users. It doesn’t make sense to pass in all the HTML code for that menu through a variable, nor does it make sense to create two versions of every page. Smarty also allows you have pieces of HTML code that appear only under certain conditions. Let’s say you have a variable called logged_in, which is set to true if the user is logged in and false otherwise. Now, you can surround your menu with smarty tags to make it only show when logged_in is true. {if $logged_in == true} This is where the HTML for the logged-in menu would go. {/if} If you inserted this variable in your html code with {$logged_in} you would see the word “true” or “false”.
There is a great deal of flexibility here, and in order to take full advantage of its power you will need to understand a little about operators and data types.
Data Types: In Smarty, your variables can hold 4 basic types of information:
Booleans – These are either true or false, as seen in the example above.
Numbers – Sometimes there are more than 2 possibilities, or you might want to show something in a different color depending on how high or low a number is. You can make conditions from numeric variables as well.
Strings – This is any text, such as a name, title, profile text, or even HTML code. Unlike booleans and numbers, if you want to base your condition on a specific String value, you’ll need to put it in quotes. Arrays – This is a grouping of one or more variables into one variable name. We’ll go into how this works later. So, here are some variants on the example above: {if $age == 21} This code will show only if $age is 21. {/if} {if $name == “Adam”} This code will show only if $name is Adam. Note the double quotes.
Operators: In addition to checking for a specific number like 21, you can check if your variable is great or less than a specific value, and even do some math.
Comparison operators: ==, >, >=, = 18} Code for only people at or over the age of 18. {/if} {if $age != 21} Code for only people who are not exactly 21. {/if} Please note that when testing if a Boolean is true, you can leave off the “== true”. These comparisons are all evaluated to be either true or false. {$logged_in} and {$logged_in == true} will always yield the same true or false value.
Math: +, -, *, / {if $starting_pay + $bonus > 20000} Addition {/if} {if $revenue > $material_costs + $labor_costs} Addition again {/if} {if $area > $length * width} Multiplication {/if}
Logical operators: &&, || These operators represent “and” and “or”, and can be used to combine more than one condition. {if $logged_in && $premium} Only show if user is logged in and a premium user {/if} {if $premium || $admin} Only show if user is premium or an admin {/if} {if ($cost > 1000) && ($revenue < 500)} Only show if cost is more than 1000 and revenue is less than 500 {/if} Just like in math, you can use parentheses to group things together that need to be evaluated first. There is virtually no limit to the complexity of the conditions you can build. There are more operators available, so you may also want to search the web for a complete list. As a final note on these conditional blocks of code, you can also save some time by adding “else” or “else if” sections. If and only if your first condition turns out false, Smarty will check these additional sections. For example: {if $age >= 21} You are over 21. Have a beer. {elseif $age >= 18} You’re not 21 yet, but at least you can vote. {else} Wow, you’re neither over 21 nor over 18. Bummer. {/if}
You can have as many elseif blocks as you want, or none at all.
Lists This is where arrays come in. Imagine you’re displaying a list of the 20 most recent users to join your site. Creating 20 different variables and repeating code for each one would be a major pain. Fortunately, you don’t have to. When working with lists, you’ll primarily use the foreach tag. Let’s say $names is an array containing a list of the names of the 20 most recent users. {foreach from=$names item=”name”} {$name} {/foreach} The code above goes through every name in the list, puts it into a new variable called $name, and then inserts $name into the HTML code with a line break after each one. Everything in the foreach block is repeated for every value in the list. Whatever you specify as “item” will become the name of a new variable to hold a value from the list each time through.
Again, there is a great deal of flexibility allowed here. Arrays can contain other arrays, so that for each item in the list you can hold more than one piece of information. To better understand this, we need to look at how arrays are structured.
Arrays: Each item in an array has both a key and a value. By default, these keys are numbers; giving you a numbered list. We usually write this as [key] => “value”. So, for example, the $names array above look something like this: [0] => “Alex”, [1] => “Linda”, [2] => “Bob”, [3] => “Jessica” With arrays, numbering generally starts at zero. However, it’s possible to store additional information by specifying your own keys. For example, a user_id or an e-mail address. [“alex@somewhere.com”] => “Alex”, [“linda@somewhere.else.com”]] => “Linda” You can then use that key in your foreach block (also called a foreach loop) to, for example, display a list of e-mail links. {foreach from=$names key=”email” item=”name”} {$name}’s e-mail address is {$email} {/foreach} However, most of the time you’re displaying lists on a website you will want more than 2 pieces of information. That’s where we use arrays inside of arrays. Let’s say for each user we want to list their first name, last name, and age. For each person we’ll have an array, and then we’ll group all those arrays together in one big array called $people. It might look something like this: [0] => Array([‘fname’] => “Alex”, [‘lname’] => “Johnson”, [‘age’] => 32), [1] => Array([‘fname’] => “Linda”, [‘lname’] => “Jackson”, [‘age’] => 29), [2] => Array([‘fname’] => “Jessica”, [‘lname’] => “Thornton”, [‘age’] => 43) I didn’t need to store anything in the key of the outer array, so I just left it as numbers. By using a descriptive key for each piece of information in the inner arrays, I’m making it easier to use this information in my foreach loop. You can access specific items in an array by using the array name followed by a period followed by the key name: {foreach from=$people item=’person’} Name: {$person.fname} {$person.lname}, Age: {$person.age} {/foreach} Each time through the foreach loop above, $person takes on the value of one of the arrays inside of $people. Then, I’m able to access information from each person’s array by specifying the name of the key.
It is possible to create much more complicated structures with arrays inside of arrays inside of arrays, and it is even possible to have a foreach loop inside another foreach loop. However, for most purposes the example above is as about as complex as you will need.
Although it is possible to hand off templates to a PHP coder with minimal explanation and allow him or her to “figure it out,” it’s best if you discuss all the variables you will need. Especially with arrays, you’ll need to agree on how the information will be organized. The sooner you both know what dynamic data will be involved, the more time you can work concurrently to get the overall task done faster.
Testing: As you’ve undoubtedly experienced in learning HTML and CSS, there will be some trial and error before you get your Smarty templates working exactly how you want and you feel confident in applying it to more complex projects. Unfortunately, you cannot test your templates without the PHP component. You should discuss plans for testing with the PHP coder, and he or she can hopefully set up pages that pass in dummy data if the back-end code isn’t finished.
Once PHP pages are in place to send all the right variables to your templates, you can make updates to the HTML/CSS or fix any bugs in your template independently of the PHP code. Ideally the PHP coder can set up with server access to upload template changes and see the results fairly immediately.
Wrap-up: Smarty is incredibly flexible, and can do a lot more things than I’ve described here. Additionally, everything can be combined to make your pages do complex things. You can have “if” blocks inside of foreach loops and vice versa, “if”s inside of “if”s, and as many layers deep as you would like to go. You may also want to look into modifiers; they allow formatting of numbers, changing case of text, and more inside of your template. You can also create tables with rows of alternating colors by naming a foreach loop and getting a count of how many times through the loop you are each time (and checking if it’s even or odd.) There’s much more possible than can be covered in one guide, but hopefully now you have enough understanding of the basics to get started, and to better understand other examples you may see out there.
Good luck!

Leave a Comment

Your email address will not be published. Required fields are marked *