Free Online Courses for Software Developers - MrBool
× Please, log in to give us a feedback. Click here to login
×

You must be logged to download. Click here to login

×

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

×

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

How to Use Advance Features in Smarty PHP Template Engine

In this article I will go through the advanced features of Smarty Template used for creating professional websites. Next, I will illustrate the database connectivity with Smarty to enable database features

In the previous article, the introduction of the Smarty template was presented. If you are new to to Smarty please refer the previous article. In this article first of all I will explain the advanced and extend features of Smarty Template and after that, I will explain how to connect Database with Smarty template and perform different operations on the said database. Let’s start with the advanced features of Smarty:

Reserved Varibles in Smarty Template

The Smarty reserved variable {$smarty} is used in accessing different kind of variables which includes request variables as well as environmental variables. These variables are explained below:

Smarty Environmental Variables

Following are the important environmental variables in Smarty:

{$smarty.now}

{$smarty.now} is the replica of timestamp function of PHP. It outputs the current Greenwich Mean Time (GMT) which is the mean solar time in Greenwich, London. {$smarty.now} can be directly passed to the Smarty date_format modifier for display. The following example will make the concept clear:

Listing 1. advanceFetr.php

<?php
require '../libs/Smarty.class.php';
$smarty = new Smarty() ;
$smarty->display( 'advanceFetr.tpl');
?> 

Listing 2. advanceFetr.tpl

<html>
<body>
<h1>Current Time</h1><br>
{$smarty.now|date_format:'%Y-%m-%d %H:%M:%S'}
</body>
</html> 

The output of the above exaplme follows below:

Figure 1. Output displaying current time and date.

{$smarty.const}

It can be used to access the values of constants of PHP directly. Let's look at the example for clear understanding:

Listing 3. advanceFetr.php

<?php
require '../libs/Smarty.class.php';
$smarty = new Smarty();
define('MIRU_VALUE','ACHAKZAI');
$smarty->display('advanceFetr.tpl');
?> 

Listing 4. advanceFetr.tpl

<html>
<body>
<h1>Constant Example</h1><br>
{$smarty.const.MIRU_VALUE}
</body>
</html> 

The output of the above exaplme follows below:

Figure 2. Output of Smarty contant variable.

{$smarty.template}

It outputs the current template name which is being executed but does not display the directory in which the template resides.

Listing 5. advanceFetr.php

<?php
require '../libs/Smarty.class.php';
$smarty = new Smarty();
$smarty->display('advanceFetr.tpl');
?> 

Listing 6. advanceFetr.tpl

<html>
<body>
<h3>Current Template Name</h3>
{$smarty.template}
</body>
</html> 

The output of the above example is given below:

Figure 3. Output of Smarty template variable.

{$smarty.current_dir}

{$smarty.current_dir} outputs the directory name in which the current executed template resides. Follow the example below for clear understanding. The PHP file will be the same, only the code listing of the template file is to be changed.

Listing 7. advanceFetr.tpl

<html>
<body>
<h3>Current Template Directory</h3>
{$smarty.current_dir}
</body>
</html> 

The output of the above example is given as:

Figure 4. Output of Smarty current template directory variable.

{$smarty.version}

It outputs the current version of the Smarty the developer is using. The version is displayed in the basis of the current template bing processed. Below is the example which displays the current version of the Smarty I am using. Again, the PHP code listing remains the same as in the previous example.

Listing 8. advanceFetr.tpl

<html>
<body>
<h3>Current Version of Smarty</h3>
{$smarty.version}
</body>
</html> 

The Output of the above example is given below:

Figure 5. Output of Smarty version variable.

Smarty Request Variables

Smarty has an alternate way of accessing the request variables which are $_COOKIE, $_GET, $_POST, $_SESSION, $_SERVER and $_ENV. The function of these variable is the same as in PHP. Below is the list of using these variables:

  • {$smarty.cookies.name} is used instead of ($_COOKIE['name']) for the cookie “name”.
  • {$smarty.get.page} is used instead of ($_GET) for displaying the value of any page from a URL.
  • {$smarty.post.value} is used instead of ($_POST['value']) for displaying “value” variable from any form.
  • {$smarty.session.userid} is used instead of ($_SESSION['userid']) for displaying the variable “userid”.
  • {$smarty.server.MY_SERVER} is used instead of ($_SERVER['MY_SERVER']) for showing the server variable “MY_SERVER”.
  • {$smarty.env.MY_PATH} is used for showing the value of system environment variable “MY_PATH”.

Smarty Built-in Functions

There are various built-in functions present in Smarty which are an essential part of the Smarty Template Engine. These built-in functions are being processed into particular PHP inline code to get best performance and good results. They are based on reserved words, therefore, a developer cannot built his owncustom functionswith the name similar to any of the built-in functions present in Smarty Template Engine. Also, there is no need to change or modify any of the the built-in functions of Smarty. Let’s start with explaining each of the important Smarty built-in functions in detail.

{append}

The {append} tag is used to append or add sub value to variable of a template at the time of processing of template. The synax of append function looks as below:

{append var='job' value='Software' index='first'}
 {append var='job' value='Engineer' index='last'}

In the above syntax, the ‘var’ attribute refers to the variable name being assigned. The attribute ‘value’ refers to the assigned value and the attribute ‘index’ refers to an index value for new element of array. The following example will make the concept even clearer:

Listing 9. advanceFetr.tpl

<html>
<body>
<h3>append Function Example</h3>
{append var='job' value='Software' index='first'}
{append var='job' value='Engineer' index='second'}
 
The first name of the job is {$job.first}.<br>
The second name of the job is {$job.second}.
</body>
</html> 

The output of the above example is as:

Figure 6. Output of Smarty append function.

{capture}

The {capture} tag is used to get the output of any of the template present inside the tags to a particular variable without displaying it. Any kind of data present inside the {capture name='myvalue'}and{/capture} tagis gathered into variable assigned in the‘name’attribute. Let’s demonstrate that with an example:

Listing 10. foot.tpl

<html>
<body>
<h6>Coyright at Smarty</h6>
</body>
</html> 

Listing 11. advanceFetr.tpl

<h3>capture Function Example</h3>
{capture name="miru"}
  {include file="foot.tpl"}
{/capture}
{$smarty.capture.miru} 

The output of the above example is given below:

Figure 7. Output of Smarty capture function.

{$variable =....}

The {$variable} dunction is a short form or small version for the Smarty {assign} function. In this, a developer can assign any sort of values directly to the Smarty template and also can assign the values to elements of array. The 'varible' in this function is not a keyword, you can use any custom name. The following examples will make the concept clear:

Listing 12. advanceFetr.tpl

<h3>variable Function in Smarty</h3>
{$name='Abbas'}
{$job='Web Developer'}
{$qual='BS(CS)'}
 
The name of Employee is {$name}.<br>
The Job Designation of {$name} is {$job}.<br>
The Qualification of {$name} is {$qual}. 

The output of the above example is given below:

Figure 8. Output of Smarty variable function.

{assign}

The {assign} function does the job of assigning variables of template at the time of processing of template. Let's look at an example:

Listing 13. advanceFetr.tpl

<h3>assign Function in Smarty</h3>
 
{assign var="job" value="Web Developer"}
{assign var="salary" value="50,000"}
{assign var="dept" value="Software"}
 
The Employee is a {$job}.<br>
His Salary is {$salary}.<br>
He belongs to {$dept} department.

The output of the above example is given below:

Figure 9. Output of Smarty assign function.

{for}

To create simpe loops in Smarty, the {for} tag is used. To stop the iteration of loop, {forelse} tag is used. The syntax of using for loop is as follow:

{for $value=$from to $to}

In the above syntax, the ‘$value’ is name of the variable, ‘$from’ is the starting value of the loop and ‘$to’ is the end value of the loop. The above syntax is for the step size of 1 in looping.

For the step size of defined or individual value, the following syntax is used:

{for $value=$from to $to step $stepValue}

Let’s have a couple of examples for the clear understanding of the above discussion:

Listing 14. advanceFetr.tpl

<h3>'for' In Smarty</h3>
{for $value=1 to 5}
    <p> 2 * {$value} = {2 * $value} <br></p>
{/for}

The output of the above example is given as:

Figure 10. Output of for tag.

The above example was for the loop having step size of 1. The following examples depicts the loop with individual step size and the usage of {forelse} tag.

Listing 15. advanceFetr.tpl

<h3>'for' tag with Individual step size</h3>
{for $value=$from to $to step 10}
    {$value}<br>
{forelse}
  Invalid
{/for}

Listing 16. advanceFetr.php

<?php
require '../libs/Smarty.class.php';
$smarty = new Smarty();
$smarty->assign('from',5);
$smarty->assign('to',50);
 
$smarty->display('advanceFetr.tpl');
?>

The output for the above example will be as follow:

Figure 11. Output of for tag with individual step size.

Let’s do some changes to make use of the {forelse} tag. I have made changes only in PHP file and the template file will remain the same.

Listing 17. advanceFetr.php

<?php
require '../libs/Smarty.class.php';
$smarty = new Smarty();
$smarty->assign('from',50); // change 5 to 50
$smarty->assign('to',5); // change 50 to 5
 
$smarty->display('advanceFetr.tpl');
?>

The output of the above example will be as follow:

Figure 12. Output of for tag invoking {forelse} tag.

{if},{else} and {elseif}

Smarty {if} {else}tags play the same role as played by the PHP ‘if’ and ‘else’ statements. In Smarty, the {if} tag should be closed with {/if} tag.Between {if} {/if} tags, {else}and{elseif} tags can also be placed for doing some other and complex operations. Furthermore, the conditional statements in PHP can also be used. The following table shows the conditional statements of Smarty equivalent to PHP conditionals.

Conditional in PHP

Smarty Equivalent

==

eq

>

gt

<

lt

||

||

&&

&&

!

not

!=

ne, neq

>=

gte, ge

<=

lte, le

Table 1. PHP equivalent conditionals in Smarty.

Let’s have an example for clear understanding of the above discussion:

Listing 18. advanceFetr.tpl

<h3>Conditional tags in Smarty</h3>
{$job = 'Web Developer'}
{if $job eq 'Android Developer'}
    Welcome to Android World!
{elseif $job eq 'iPhone Developer'}
    Welcome to Apple World!
{elseif $job eq 'Web Developer'}
    Welcome to Real World of Website Development!
{else}
    Sorry, you came to the wrong world.
{/if}
<br>
<br>
{$job2 = 'Android Developer'}
{if $job == 'Web Developer' && $job2 == 'Android Developer'}
   This guy belongs to Software Company
{/if}
<br>
<br>
{$salary = '22,000'}
{if $salary >= '50,000'}
      The Employee is a Senior Software Engineer
{elseif $salary >= '30,000'}
      The Employee is a Junior Software Engineer
{elseif $salary < '30,000'}
      The Employee is an Internee    
{/if} 

Let’s look at the output:

Figure 13. Output of Conditional tags in Smarty.

{include}

In Smarty, the {include} tag is used for adding or including other template files into current working template. All the varibles present in the included template will also be available to the current template. For adding the path of the template file, the {include} tag must have an attribute of the file containing path of the template which is to be added. The following example will make the above discussion clear:

Listing 19. advanceFetr.tpl

<h3>'include' in Smarty Example</h3>
 
<h4>Head Section</h4>
{include file='head.tpl'}
 
<h4>Body Section</h4>
{include file="body_file.tpl"}
 
<h4>Footer Section</h4>
{include 'foot.tpl'}

The output for the above example is as follow:

Figure 14. Output of include tag in Smarty.

{literal}

In Smarty, the {literal} tags are used to let a block of data in exactly the same way as it appears without the intervention of any additional Smarty tags. {literal} tags are basically used for adding CSS blocks or Javascripts blocks. Look at the below example for clear understanding:

Listing 20. advanceFetr.tpl

<h3>literal tag in Smarty</h3>
<p id="colour">By clicking the below button, the colour of this paragraph will be changed!!!</p>
<button onclick="clrChange()">Click Here!</button>
 
{literal}
<script>
function clrChange() {
    var clr = document.getElementById("colour");
    clr.style.color = "green";
}
</script>
{/literal}

Here’s the output:

Figure 15. Output of literal tag in Smarty.

Database connectivity using Smarty and PHP

Connection with database and performing different operations using Smarty and PHP is a bit different than using simple PHP and HTML. I am having XAMPP server and throughout the rest of example, I will go through the same. First of all, create a database ‘smartyDB’ in XAMPP and create a table ‘course’ having 5 columns. You can use any name you wish and have any number of columns as you want. Add some data in the table as illustrated below:

Figure 16. Columns alongwith data in course table.

Now going back to the code, first create a database connection and necessary steps to undergo database connection without having any error. Then in the template file write the code for printing the data from the table as the following code listings illustrates:

Listing 21. advFtrDB.php

<?php
 
require '../libs/Smarty.class.php';
 
$smarty = new Smarty;
 
$smarty->compile_check = true;
$smarty->debugging = false;
$smarty->use_sub_dirs = false;
$smarty->caching = true;
 
$connect = mysqli_connect("localhost","root","");
 
if (!$connect) {
    die("Connection Unsuccessful: " . mysqli_connect_error());
}
$selectDB = mysqli_select_db($connect,"smartydb") or die("Could not select Database");
$query = mysqli_query($connect,"SELECT * FROM course") or die("Query failed : " . mysql_error());
while ($result = mysqli_fetch_assoc($query))
{
 $data[] = $result;
}
 
$smarty->assign('parts', $data);
$smarty->display('advFtrDB.tpl');
 
mysqli_close($connect);
?>

Listing 22. advFtrDB.tpl

<html>
<head>
<title>Course</title>
</head>
<body>
      <h1>Courses Information</h1>
 
{section name=parts loop=$parts}
   
      <h2>{$parts[parts].course_name} ({$parts[parts].course_id})</h2>
  
      <h3>By {$parts[parts].course_teacher}</h3>
      {$parts[parts].course_description}
      {/section}
</body>
</html>
 

And the output for the above listings will be as follow:

Figure 17. Displaying content present in course table.

In the above example, I have retrieved the data present in the ‘course’ table of ‘smartydb’ database. At the time of compilation of this example, there were three set of data (rows) present in the database which are shown in the above figure. In the template file, the {section} tag contains two attributes, name and loop. The ‘name’ attribute should have a value which will be used in the array for displaying the content fetched from the database. The ‘loop’ attribute play the role to loop for every data items present in the $data variable of the PHP file, the data of which were assigned to ‘parts’ variable.

Conclusion

Being an extended version of the previous article, this article was about the advanced features of Smarty PHP template. First in the advanced features were the reserved variables present in Smarty which consists of Request variables and Environmental variables. Then the different Built-in functions and tags present in Smarty were discussed. All of these Smarty functions and tags were also illustrated with code listings along with output. Finally, the connectivity of database with Smarty and PHP and the necessary steps required for database connection and way of retrieving data from database and displaying it through Smarty template were also stated. After going through the both tutorials of Smarty, one can easily create advance websites quite fast and easy to maintain.

Links

http://www.smarty.net



I am Computer Science Graduate having hands-on experience in Android, PHP, MySQL, CSS, Javascript, HTML etc.

What did you think of this post?
Services
[Close]
To have full access to this post (or download the associated files) you must have MrBool Credits.

  See the prices for this post in Mr.Bool Credits System below:

Individually – in this case the price for this post is US$ 0,00 (Buy it now)
in this case you will buy only this video by paying the full price with no discount.

Package of 10 credits - in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download few videos. In this plan you will receive a discount of 50% in each video. Subscribe for this package!

Package of 50 credits – in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download several videos. In this plan you will receive a discount of 83% in each video. Subscribe for this package!


> More info about MrBool Credits
[Close]
You must be logged to download.

Click here to login