Home » Smarty

An Introduction to Smarty Template Engine

29 June 2008 396 views Popularity: 1% Share/Bookmark

email

Smarty is a template engine for PHP. More specifically, it facilitates a manageable way to separate application logic and content from its presentation. This is best described in a situation where the application programmer and the template designer play different roles, or in most cases is not the same person.

One day the programmer needs to change the way the article content is retrieved (a change in application logic.) This change does not affect the template designer, the content will still arrive in the template exactly the same. Likewise, if the template designer wants to completely redesign the templates, this requires no changes to the application logic. Therefore, the programmer can make changes to the application logic without the need to restructure templates, and the template designer can make changes to templates without breaking application logic.

One design goal of Smarty is the separation of business logic and presentation logic. This means templates can certainly contain logic under the condition that it is for presentation only. Things such as including other templates, altering table row colors, upper-casing a variable, looping over an array of data and displaying it, etc. are all examples of presentation logic. This does not mean that Smarty forces a separation of business and presentation logic. Smarty has no knowledge of which is which, so placing business logic in the template is your own doing. Also, if you desire no logic in your templates you certainly can do so by boiling the content down to text and variables only.

With Smarty, the PHP syntax doesn’t contain print. Instead, the programmer passes these arrays to the designer by assigning them to Smarty templates. Then it’s the designer’s job to make them look good in the web page without worrying about the PHP code. The use of Smarty comes at its best when you have different programmers and designers and you don’t want the designer to access the system core.

Smarty makes the job of the designer as well as the programmer very easy. The key tasks performed by them can be listed as follows.

The Programmer’s tasks:

• Extract database elements with a simple query on the database.

• Validate and manipulate the data by performing business logic on it.

• If needed, change the data access methods and the business logic without interfering with the designer’s work. For example, the whole system could migrate from MySQL to PostgreSQL without the designer making a single change.

The Designer’s tasks:

• Create HTML designs without affecting or jeopardizing the programmers PHP code. The designer only needs to be concerned with placing the content elements that the programmer has agreed to provide.

• Make changes to the design without consulting or interfering with the programmer’s work.

• Stop worrying about technical changes to the site breaking the way that the site appears to viewers.

Some of the Smarty Features are:-

No template parsing overhead, only compiles once. It is smart about recompiling only the template files that have changed.

One of the unique aspects about Smarty is the template compiling. This means Smarty reads the template files and creates PHP scripts from them. Once they are created, they are executed from then on. When a file is called from the web, the php file is parsed and smarty compiles the results from the template files used. When that same page is called and the template files have not been altered smarty will use the compiled version which causes the server to not need to recompile the pages.

Built-in caching support

Smarty has the ability to use cache. Hence, it is extremely fast. Smarty caches the output of the template contents, saving the overhead expense involved in retrieving data from a data source. Smarty caches the output of the template with this data from the data source, and saves you from having to connect to the database every time your Web page is accessed.

Smarty is again smart enough to allow you to specify what should or should not be cached. In fact, you can have cached and un-cached portions on the same template page, as Smarty allows you to specify exactly what you don’t want cached (like that stock ticker at the bottom of the page, which is frequently changed) and what you do want cached (such as your navigation bar, which is seldom changed). You can also set the cache expiry time so that your template output is cached only for a specific length of time. You can thus achieve the middle-ground between having up-to-date dynamic content and quick-to-load Web pages.

You can make custom functions and custom variable modifiers, so the template language is extremely extensible.

Smarty provides built-in and custom functions for use in your templates. These functions are like the API of Smarty templates, except that custom functions can be modified but not built-in functions. In the custom functions, you can assign template variables during the execution of the templates.

Variable modifiers give template designers the ability to modify template variables. Variable modifiers can be applied to variables, custom functions or strings. To apply a modifier, specify the value followed by the | (pipe) and the modifier name. A modifier may accept additional parameters that affect its behavior. These parameters follow the modifer name and are separated by : (colon).

{$title|upper} = Applying modifier to a variable. This will change the variable text into uppercase.

{$title|truncate:40:”…”} = Applying modifier with parameters. This will truncate the variable text into 40 characters followed by three dots (…).

It is possible to embed PHP code right in your template files, although this may not be needed (nor recommended) since the engine is so customizable.

php tags allow php to be embedded directly into the template. This is for advanced users only, not normally needed.

{php}

// including a php script directly

// from the template.

include(“/path/to/display_weather.php”);

{/php}

Presence of conditional statements (if/elseif/else) and loops (foreach/section)

{if} statements in Smarty have much the same flexibility as PHP if statements, with a few added features for the template engine. Every {if} must be paired with an {/if}. {else} and {elseif} are also permitted. All PHP conditionals are recognized, such as ||, or, &&, and, etc.

{if $name eq “Fred”}

Welcome Sir.

{elseif $name eq “Wilma”}

Welcome Ma’am.

{else}

Welcome, whatever you are.

{/if}

Template sections are used for looping over arrays of data. All section tags must be paired with /section tags. foreach loops are an alternative to section loops. foreach is used to loop over a single associative array. foreach tags must be paired with /foreach tags. Both section and foreach loops can be nested, and the nested loops names must be unique from each other.

Config Files

Config files are configuration files where you can store global template variables. This allows you to store variables that should affect every template (i.e. global variables) in a central location. A good example of such a variable would be the color scheme for your templates. Normally if you wanted to change the color scheme of an application, you would have to go through each and every template file and change the colors. With a config file, the colors can be kept in one place, and only one file needs to be updated.

The other variables that you can store in a config files are like page title, page information, database information, etc.

Plugin architecture

The Smarty plug-in architecture was introduced in version 2.0 and allows you to customize Smarty to suit your purposes. With plug-ins, you can create your own template functions, variable modifiers and filters. It is used for almost all the customizable functionality of Smarty. This includes: functions, modifiers, block functions, compiler functions, prefilters, postfilters, outputfilters, resources, and inserts.

Source:

1) Smarty Manual, Monte Ohrt, Andrei Zmievski, 2001-2005 New Digital Group, Inc.

2) Smarty – PHP Template Programming and Applications, Lucian Gheorghe, Hasin Hayder, Joao Prado Maia.

3) http://www.sitepoint.com/article/smarty-php-template-engine

Related posts:

  1. Installing the Smarty Template Engine
  2. Templating in Smarty
  3. Creating selection list, using foreach and section loop in Smarty
  4. Pagination in PEAR and Smarty
  5. Using database in PEAR and Smarty
  6. File Upload in PEAR and Smarty
  7. An introduction to RSS
  8. Magento: Send Transactional Email
  9. Magento: How to call static block from template file?
  10. An Introduction to PEAR