PHP Smarty Template

Here are the details of Template benefits, list of templates which are currently running, Installation and setup, and finally sample codes. Here I have also provided solutions for some of the common problems faced by a programmer when they start using smarty template or any template. Examples are divided in two section:
One telling about sample codes and usage of smarty software and another in telling solutions about general problem we face when we use any kind of templete.

Why use a template?

We use template for separating the application logic from presentation logic. Programmer handles the application side and presentation side will be maintained by designer. Designer doesn’t have to be master in application language. So template try to present the code in such a way so that designer can easily understand or don’t have to go through all the details of coding.

We have number of templates frameworks available in open source as PHP template. Some of them are:-
Smarty PHP template,
PEAR::HTML_Template_Flexy PHP template,
PEAR::HTML_Template_IT PHP template,
PEAR::HTML_Template_PHPLIB PHP template,
PEAR::HTML_Template_Sigma PHP template,
PEAR::HTML_Template_Xipe PHP template,
patTemplate PHP template.

Why use Smarty template?

To answer this, I will use the answer Smarty itself has written. Reading this you will become familiar with more template benefits and what smarty provides.

* Designers can't break application code. They can mess with the templates all they want, but the code stays intact. The code will be tighter, more secure and easier to maintain.
* Errors in the templates are confined to the Smartys error handling routines, making them as simple and intuitive as possible for the designer.
* With presentation on its own layer, designers can modify or completely redesign it from scratch, all without intervention from the programmer.
* Programmers aren't messing with templates. They can go about maintaining the application code, changing the way content is acquired, making new business rules, etc. without disturbing the presentation layer.
* Templates are a close representation of what the final output will be, which an intuitive approach is. Designers don't care how the content got to the template. If you have extraneous data in the template such as an SQL statement, this opens the risk of breaking application code by accidental deletion or alteration by the designer.
* You are not opening your server to the execution of arbitrary PHP code. Smarty has many security features built in so designers won't breach security, whether intentional or accidental. They can only do what they are confined to in the templates.

What is so tough about writing <? echo $title; ?> instead of {$title}?

Making things easier to read wasn't a design goal, but more of a side effect. Using templates has huge benefits, many of which have been explained above. Since we are in a template environment anyways, {$title} is less extraneous than <? echo $title; ?>, especially when you start looking at it in long pages of content, so it was pretty evident that a simpler syntax helps to make templates easier to read and maintain.

Installation of smarty template

1. Download smarty. You will get “libs” folder. Libs folder will have:-
internals, plugin, configFile.class.php, debug.tpl, smarty.class.php and smarty_compile.class.php.
2. Now create four dirs:- (under a folder like /smarty/)
Smarty/templates/
Smarty/template_c/
Smarty/cache/
Smarty/configs/

template_c will have your all compiled template.

3. Now you will store all your templates in /templates/ folder.
Your config file will be placed at /configs/ folder.
Smarty will store cache file at /cache/ folder, if you have enabled cache. You will enable cache through setting.
Give /template_c and /cache proper permission for writing.

Now start coding with Smarty Template

Your first smarty page:- index.php

// Full path to smarty class-
require ‘your_path/Smarty.class.php’;

$smarty = new Smarty();

$smarty->template_dir = ‘your_path/smarty/templates’;
$smarty->compile_dir = ‘your_path/smarty/templates_c’;
$smarty->cache_dir = ‘your_path/smarty/cache’;
$smarty->config_dir = ‘your_path/smarty/configs’;

# now assign variables (defined in template)
$smarty->assign(‘name’, ‘Smarty Enabled File’);
$smarty->display(‘index.tpl’); // template file of index.php

Now index.tpl

<html>
<head> <title> My First Smarty File </title> </head>

<body>
{$name}
</body>
</html>

This was the simplest example of smarty template.

Now I will tell you about smarty config file. Smarty config file can have, as you can understand, configuration directives for whole site with some control statement for controlling the config directive usability also. Through this you can tell which variable in config file will be printed or not. The variable can be maintained for section wise also.

Mentioning Config file in template-

{config_load file = ‘config.conf’} at top of the template page.

You can use variables of config file like this in template:-

<title> {#pageTitle#} </title>

See two ‘#’ sign before and after variable.

In smarty config file, variable will be declared like this:-
#global variable
pageTitle = 'testing'

You can use double quotes or avoid it in config file. In general use double quotes for string.

Smarty config file can have sections

# student section
[student]
myVars = '…';

# hidden section. Database section.
[.database]
databaseName = 'IGNOU';
databaseUser = 'smarty';

Sample config file:

# this is comment

# global vars
pageTitle = 'Testing'
bodyBgColor = 'gray'

[student]
pageTitle = 'Student Info Page'
bodyBgColor = 'orchid'

Use of template variables
1. {config_load file='config.conf' section='student'}
or
2. {config_load file='config.conf'}

First will give preference to student section variables in config file. So, when variables in template file do not found in student section then it will look in global variable section.

Documentation for using smarty template
You will find full document of smarty template uses at

Smarty Document
Onlamp


More Smarty Example:

{strip} {/strip} is used in template for stripping whitespace from source.

One dimension array loop in smarty
/* For loop (1). This code in php file. */
$smarty->assign('student', array('bob','jim','joe','jerry','fred'));

This code will be used in template (tpl) file. This will loop all the students’ name.
{section name=mysec loop=$student}

{$student[mysec]}

{/section}

Looping Associative array in smarty
In PHP file:
/* For loop (2) */
// assign an associative array of data
$smarty->assign('users', array(
array('student' => 'bob', 'phone' => '555-3425'),
array('student' => 'jim', 'phone' => '555-4364'),
array('student' => 'joe', 'phone' => '555-3422'),
array('student' => 'jerry', 'phone' => '555-4973'),
array('student' => 'fred', 'phone' => '555-3235')
));

In Template (tpl) file:
Loop in associative array:

<table><tbody>
{section name=mysec2 loop=$users}
{strip}
<tr>
<td>{$users[mysec2].student}</td>
<td>{$users[mysec2].phone}</td>
</tr>
{/strip}
{/section}
</tbody></table>

Another example:

PHP:
For $i from 0 to 10
$extra[$i]['name'] = '';
$extra[$i]['type'] = '';
$extra[$i]['total'] = '';
End For

Smarty:
{section name=additional loop=$extra}
"{$extra[additional].name}",
"{$extra[additional].type}",
"{$extra[additional].total} {$extra[additional].currency}",
"{$extra[additional].number}"
);
{/section}

Using PHP tag (code) in template (tpl) file:

For running php codes directly in template page, you can use {php} {/php}.

{php}
echo '<div><strong>Hello</strong></div>';
{/php}

Variable modifiers example: capitalize, escape and display date.
In tpl file This will capitalize name variable value:
{$namecapitalize}
Date: {$smarty.nowdate_format:"%d-%m-%Y"}

Include file in template file:
{include file="footer.tpl" title="Header below body"}

Smarty predefined variable
You can use PHP predefined variable in smart template (tpl) file:
Script Name: {$smarty.server.SCRIPT_NAME}
PATH: {$smarty.env.PATH}
PHP_VERSION: {$smarty.const.PHP_VERSION}

Smarty "Capture" Function:
{capture name=banner assign=testAssign}
Hello Testing
{/capture}
Now checking for banner is assigned or not!
{if $smarty.capture.banner ne ''}
<div id="banner">{$smarty.capture.banner}</div>
{/if}
I have also used assign=testAssign, So I can use this also-
{$testAssign}

About Custom Smarty Function

Here I am CCP of test page:


You will find running example of the above examples here and more:
Page:header.php

Page:header.php

This is a header file you will like to create so that you don’t have to write same code again and again in all page. It will be included in PHP file.

<?php
error_reporting(E_ALL);
// put full path to Smarty.class.php
define('SMARTY_DIR', '/var/www/html/smarty_libs/'); // Must end with trailing slash.
// path to Smarty windows style
//define('SMARTY_DIR', 'c:/webroot/libs/Smarty-v.e.r/libs/');

require(SMARTY_DIR . 'Smarty.class.php');

$smarty = new Smarty();

// Compile each time and not use caching. For development env. only.
// You can also use $smarty->cache_lifetime=0; for this.
$smarty->force_compile = true;

$smarty->caching = true; // will be used only when $this->force_compile = false

$smarty->template_dir = '/var/www/html/myApp/myApp_smarty/templates';
$smarty->compile_dir = '/var/www/html/myApp/myApp_smarty/templates_c';
$smarty->cache_dir = '/var/www/html/myApp/myApp_smarty/cache';
$smarty->config_dir = '/var/www/html/myApp/myApp_smarty/configs';

?>

Page:index.php
<?php
require 'header.php'; // smarty header file

// Block 1
$smarty->assign('name', 'satya prakash'); // assign value to var. name.
$smarty->assign('address', '45th & Harris');

/* Index Page */
# <if not cached>
if(!($var1 = $smarty->is_cached('index.tpl'))) :

/* For testing loop (1) */
$smarty->assign('student', array('bob','jim','joe','jerry','fred'));

/* For testing loop (2) */
// assign an associative array of data
$smarty->assign('users', array(
array('student' => 'bob', 'phone' => '555-3425'),
array('student' => 'jim', 'phone' => '555-4364'),
array('student' => 'joe', 'phone' => '555-3422'),
array('student' => 'jerry', 'phone' => '555-4973'),
array('student' => 'fred', 'phone' => '555-3235')
));

endif; # </if not cached>

// template file of index.php
$smarty->display('index.tpl');
?>

Page:css.css
Css.css file will be included in template file. It will be located in reference with index.php.

.testDiv {color:#003366}

Page:templates/header.tpl

As you can see below “{* …Comment… *}” is used for comment in template (tpl) file.
File can be included with {include file="header.tpl" title="Header below body"} in template file.

{* Heading <H1> in Body *}
<h1>Heading</h1>

PAge:templaets/Index.tpl
<html>
<head>
<title>Testing</title>
<link rel="stylesheet" href="css.css" type="text/css" />
</head>
<body>
{include file="header.tpl" title="Header below body"}

<div class="testDiv">
Hello, {$namecapitalize}!
<br>
Address:{$addressescape}
<br>
Date: {$smarty.nowdate_format:"%d-%m-%Y"}
</div>
<hr noshade="true" />

<strong> Learning Smarty: </strong><br>
<br>
Script Name: {$smarty.server.SCRIPT_NAME}
<br>
{* display the system environment variable "PATH" *}
PATH: {$smarty.env.PATH}
<br>
Constants: {$smarty.const.PHP_VERSION}
<br>
{* The template being processed *}
Template processed: {$smarty.template}

<br><br>
{* we don't want to print a div tag unless content is displayed *}
==================================
<div style="border:1px solid brown">
<pre>
Smarty "Capture" Function
{capture name=banner assign=testAssign}
Hello Testing
{/capture}
Now checking for banner is assigned or not!
{if $smarty.capture.banner ne ''}
<div id="banner">{$smarty.capture.banner}</div>
{/if}
I have also used assign=testAssign, So i can use this also-
{$testAssign}
</pre>
</div>
================================== <br>
For running php codes directly in template page, you can use {php} {/php}.

{php}
echo '<div><strong>Hello</strong></div>';
{/php}
==================================<br>
<b>Loop:</b><br>
{* Here I have inserted some newline in middle of tr and td. When I will remove strip tag, it will show in source codes. But after using strip tag, it will strip whitespace. *}
<table>
{section name=mysec loop=$student}
{strip}

<tr bgcolor="{cycle values="#eeeeee,#dddddd"}">

<td>{$student[mysec]}</td>

</tr>
{/strip}
{/section}
</table>
<b>Loop in associative array:</b><br>
<table>
{section name=mysec2 loop=$users}
{strip}
<tr bgcolor="{cycle values="#aaaaaa,#bbbbbb"}">
<td>{$users[mysec2].student}</td>
<td>{$users[mysec2].phone}</td>
</tr>
{/strip}
{/section}
</table>

==================================<br>

{include file="footer.tpl" title="Header below body"}
</body>
</html>