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 Create Websites in Smarty PHP Template

In this article, we will see an introduction to Smarty Template and the different features related to it, and also its use when creating websites.

Nowadays , the number of templates and frameworks are increasing . Different highly qualified and professional website developers and website designers are introducing templates and framworks month by month. This article is about one such website development template known as Smarty Template used for developing websites with quite ease.

Smarty Template

Smarty is basically a PHP template engine used for separating the HTML/CSS code (known as presentation) from PHP code (known as application logic). Smarty enables a convenient way for separating PHP code from HTML/CSS code.

Important features of Smarty

Following are few of the important features of Smarty PHP Template that makes Smarty unique in many ways:

  • One of the best feature of Smarty is that it avoids parsing overhead of the template, rather it is compiled only once.
  • Smarty Template is very fast and avoids loading for long time.
  • Developer can create his/her own unlimited variables and functions for different purposes.
  • Smarty allows nesting of unlimited Smarty components like if….else, sections etc.
  • Constructs like {if} ... {elseif} ... {else} ... {/if} are delivered to the parser of PHP which makes the syntax of {if…} expression as easy and simple as anyone likes to use it.
  • When any of the template files are modified, Smarty is fast and keen in recompiling such files.
  • For the contents of templates to be managed easily, Smarty uses the feature of Template Inheritance which allows you to define one or more parent templates which can be extended by child templates.
  • To speed up calls to fetch() and display() functions, Smarty has the built-in support for caching.

Why Smarty?

The question that arises in every mind is that why use Smarty. The answer can be found easily by looking through the following aims and goals of Smarty:

  • Smarty template is a front end while PHP code is back end in developing a project.
  • Smarty enables clear separation of HTML/CSS code from PHP code.
  • Smarty enables designers and programmers to reduce the development cycle.
  • It is free and open source, anyone can use it.
  • The syntax of Smarty is easy to understand and no pre-requisite and high knowledge of PHP is required.
  • It is used as a complement for PHP but not replacing PHP.
  • It is easy and fast to maintain.
  • It provides high level of security and cannot be easily hacked.

Installation of Smarty PHP Template

Before getting started with development using Smarty, first of all, I will present the procedure of installing Smarty PHP Template. Download the latest version of Smarty (.zip) by clicking here. Extract it and you will see the following files as shown in the figure:

Figure 1. Files and Folders of Smarty package.

Rename the folder "demo" with the name of your choice or leave it as default. It is up to you and not mandatory to change. Web server running PHP 5.2 or greater is required for Smarty. Place the Smarty folder in "www" folder of Wampp if you are using Wampp Apache server or in "htdocs" folder of "Xampp" if you are having Xampp Apache server. As I am working with "Wampp" Apache Server, so we will use it in in this article.

Nothing to do with the 'libs' folder, just leave it as is. The 'libs' folder basically contains the files which are shared among all applications. Therefore, these files should not be edited. To use the services of lib files, just include them in your file via "require_once()" function, and inside the function, provide the "Smarty.class.php" file as require_once('Smarty.class.php'). Including "Smarty.class.php" file will allow access to all the functionalities contained inside this file. Initialize an Object of Smarty to display the template file or obtain some other functionality through Smarty variable. I will illustrate it later when an application program is presented which will be done in the next section. In the "demo" folder, you will find the sub-folders as shown in the following image:

Figure 2. Sub-folders inside demo folder

Among these folders, we only have to deal only with the "templates" folder which contains the HTML (front-end) files. The files inside the "templates" folder should be saved with the extension as ".tpl" rather than ".html" or ".htm" as it does not render the components of Smarty when the template file is not saved with ".tpl". The PHP files should be saved in the "demo" folder without creating another sub folder.

Syntax of Smarty PHP Template

The tags of the Smarty Template are enclosed within '{' and '}' delimiters. If you are using content outside of the delimiters, then it will be displayed as unchanged or static content. Whenever any template tag is found by Smarty, it tries to compile them and display the suitable output in its place.

Smarty Template Variables

Like PHP variables, the variables of Smarty Template also starts with the dollar ($) sign. Variables may contain letters, numbers and letters and underscores. You can also reference the arrays by numerical indexing or non-numerical indexing. Furthermore, you can also reference methods and object properties. The following example will make the concept clear:

Listing 1. display.php

  <?php
     require '../libs/Smarty.class.php';
     $smarty = new Smarty();
     $smarty->assign('myname', 'Mirwaise');
     $smarty->assign('dept', 'CS');
     $smarty->assign('skill', 'PHP');
     
     $smarty->display('display.tpl');
     ?> 
  

Listing 2. display.tpl

  My Name is : {$myname}
  <br>
  I am student of {$dept} Department.
  <br>
  My skills contain {$skill} as one of the best. 
  

The method "assign()" in PHP file is used to assign variables to the template. Here is the output of the example:

Figure 3. Assigning variables in Smarty

Variables in Array

Similar to PHP syntax, the arrays in Smarty can be referenced by array indexing. The following example shows how to do it:

Listing 3. smartyArray.php

   <?php
     require '../libs/Smarty.class.php';
     $smarty = new Smarty();
     $smarty->assign('Info', array( 'Miru', 'miru@bool.com', array('25-12-91', 'Achakzai')));
     $smarty->display('smartyArray.tpl');
     ?> 
  

Listing 4. smartyArray.tpl

  MySelf: {$Info[0]}<br><br>
  Example Email: {$Info[1]}<br><br>
  DOB: {$Info[2][0]}<br><br>
  Belongs to:  {$Info[2][1]} 
  

Here is the output to the above example:

Figure 4. Array Indexing in Smarty

Referencing Associative arrays:

The variables of associative array can also be referenced by providing a particular key after a dot (.) symbol. The following example shows how to do it:

Listing 5. associativeArray.tpl

  My Demo Zip Number is : {$NewInfo.zip}<br><br>
  Study Government Department is : {$NewInfo.study}<br><br>
  BS Study Type: {$NewInfo.category.BS}<br><br>
  MS Study Type: {$NewInfo.category.MS}<br><br> 
  

Listing 6. associativeArray.php

  <?php
     require '../libs/Smarty.class.php';
     $smarty = new Smarty();
     $smarty->assign('NewInfo',
         array('zip' => '12345',
               'study' => 'ICT',
               'category' => array('BS' => 'Scholarship',
                                'MS' => 'Self')
                                )
              ); 
     $smarty->display('associativeArray.tpl');
     ?> 
  

Here is the output:

Figure 5. Associative Array in Smarty

Smarty Template Comments:

Comments in Smarty Template are enclosed within asterisks (*) which is further enclosed by delimiter ({ }) tags. Unlike HTML Comments (), the comments in Smarty Template are not shown in the output of the template. To make internal notes in the template, Smarty Template comments are much more useful as no one can see them but only the developer can understand what he/she had done there. Let us look at an example program of different types of comments which is not only restricted to single line comments but multiple line comment are also presented.

Listing 7. comments.php

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

Listing 8. comments.tpl

  {* This is simple Single Line Comment and will not be displayed *}
  <html>
     <body>
        {* Now Bro, this is a Multi-Line Smarty Template
        Comment and this will
        also not displayed !!!!!!!!
        *}
        <h1>Smarty Template</h1>
        {* The following line will not be displayed *}
        {* 
        <h3>Miru</h3>
        *}
        <p> In this section, we discuss about Comments in Smarty Template. </p>
     </body>
  </html> 
  

The following figure shows the output of the comments example:

Figure 6. Comments Example in Smarty

Functions in Smarty Template

In Smarty, the Syntax of functions consists of function name followed by a single or multiple attributes. The function and its attributes are surrounded by delimiters. Let's look at an example for clear understanding of the concept of functions in Smarty:

Listing 9. funcSmarty.php

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

Listing 10. funcSmarty.tpl

  {include file="head.tpl"}
  {include file="body.tpl"}
  {include file="foot.tpl"} 
  

Listing 11.head.tpl

  <!doctype html>
  <html>
     <body>
        <h1>Introduction To Smarty</h1>
     </body>
  </html>
  body.tpl
  <!doctype html>
  <html>
     <body>
        <p>This Section Contains the Body of the Page and discusses the features of Smarty Template</p>
        <h3>Function in Smarty</h3>
        <p>In Smarty, function plays the same role as in other languages.<br>
           Function is basically a group of statements which together does a particular task.<br>
           <strong>You can deal with both custom functions or built-in functions</strong>
        </p>
     </body>
  </html> 
  

Listing 12. foot.tpl

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

The Output of the above example is presented below:

Figure 7. Functions Example in Smarty

In the above 'funcSmarty.tpl' file, I have used an 'include' function, which is a type of built-in function having an attribute 'file'. This function is used to include any other template within the same file and post all the activities that are present in that template. The attribute 'file' is used to define the required file that has to be included in the present file.

Smarty Variable Modifiers

In Smarty Template, the variable modifiers is applicable to variables, strings and custom functions. The syntax for applying a modifier to a variable is to specify the particular value and then followed by a pipe sign (|) and then the type of modifier you wish to apply. If you wish to apply additional parameters for changing the behavior of a modifier, then place a colon (:) after the name of the modifier and then place the additional behavior parameter. Let's discuss the different variable modifiers one by one:

cat

The cat modifier is used to add or concatenate a value to the variable. The following example illustrates it clearly:

Listing 13. modifierExamples.php

// Displaying
  <?php
  require '../libs/Smarty.class.php';
  $smarty = new Smarty();
  $smarty->assign('myname', "Mirwaise Khan");
  $smarty->display('modifierExamples.tpl');
  ?> 
  

Listing 14. modifierExamples.tpl

  Complete Name (without cat modifier): {$myname}<br><br>
  Complete Name (with cat modifier): {$myname|cat:' Achakzai'} 
   

The output for the above example is given below:

Figure 8. Concatenation modifier example in Smarty

lower

The lower modifier is used to change the variable value to a lower-case. The example below makes it clear to understand.

Listing 15. modifierExamples.php

  <?php
  require '../libs/Smarty.class.php';
  $smarty = new Smarty();
  $smarty->assign('myname', "Mirwaise Khan");
  $smarty->display('modifierExamples.tpl');
  ?> 
  

Listing 16. modifierExamples.tpl

  Name (without lower modifier): {$myname}<br><br>
  Name (with lower modifier): {$myname|lower} 
  

Here is the output for the above example:

Figure 9. Lower modifier example in Smarty

upper

The lower modifier is used to change the variable value to a lower-case. It is explained in the example below.

Listing 17. modifierExamples.php

  <?php
  require '../libs/Smarty.class.php';
  $smarty = new Smarty();
  $smarty->assign('course', "computer science");
  $smarty->display('modifierExamples.tpl');
  ?> 
  

Listing 18. modifierExamples.tpl

  Course Name (without upper modifier): {$course}<br><br>
  Course Name (with upper modifier): {$course|upper} 
  

Below is the output for the above stated example:

Figure 10. Upper modifier example in Smarty

capitalize

The capitalize modifier is used to capitalize the first letter of each word[%1] present in a variable. See the below example for illustration.

Listing 19. modifierExamples.php

  <?php
  require '../libs/Smarty.class.php';
  $smarty = new Smarty();
  $smarty->assign('warning', "do not go outside during office hours");
  $smarty->display('modifierExamples.tpl');
  ?> 
  

Listing 20. modifierExamples.tpl

  Warning (without capitalize modifier): {$warning}<br><br>
  Warning (with capitalize modifier): {$warning|capitalize} 
  

Here is the ouput for clear understanding:

Figure 11. Capitalize modifier example in Smarty

default

The default modifier sets a variable to have a default value. It takes only one argument. This happens when a variable contains an empty string or a variable is unset. In such case, the provided default value is printed. Otherwise, if the variable contains any value, then the default modifier does not work and displays the value provided to the variable. The following example makes the concept clear.

Listing 21. modifierExamples.php

  <?php
  require '../libs/Smarty.class.php';
  $smarty = new Smarty();
  $smarty->assign('cricket', 'I love to Play Cricket');
  $smarty->assign('football', '');
  $smarty->display('modifierExamples.tpl');
  ?> 
  

Listing 22. modifierExamples.tpl

  {$cricket|default:'Null Value'}
  {$hockey|default:'Null Value'}
  {$football|default:'No Football comments provided'} 
  

Below is the pictorial output for the above stated example:

Figure 12. Default modifier example in Smarty

nl2br

The nl2br modifier is used to convert the (line breaks) '\n' to in HTML to make the possibility of having a new line in the variable.

Listing 23. modifierExamples.php

  <?php
  require '../libs/Smarty.class.php';
  $smarty = new Smarty();
  $smarty->assign('line', "Come On Let's Play:\nCricket");
  $smarty->display('modifierExamples.tpl');
  ?> 
  

Listing 24. modifierExamples.tpl

  {$line|nl2br} 
  

Here is the output:

Figure 13. nl2br modifier example in Smarty

count_characters

The count_characters modifier counts the total number of characters present in a variable. By default, it counts the total characters without spaces, but if you wish to count the total characters with spaces, then write 'true' after count_characters.

count_words

The count_words modifier counts the total number of words present in a variable. See the following example for clear understanding.

Listing 25. modifierExamples.php

  <?php
  require '../libs/Smarty.class.php';
  $smarty = new Smarty();
  $smarty->assign('num', 'The Quich rown Fox Jumps over the Lazy Dog');
  $smarty->display('modifierExamples.tpl');
  ?> 
  

Listing 26. modifierExamples.tpl

  Text Provided: {$num}<br><br>
  Total Characters (without spaces): {$num|count_characters}<br>
  Total Characters (with spaces)    : {$num|count_characters:true}<br><br>
  Total Words                : {$num|count_words} 
  

The output for the above program example is stated below:

Figure 14. Count_ characters and Count_words modifier example in Smarty

count_sentences

The count_sentences modifier counts the total number of sentences present in a variable. The modifier identifies sentence being terminated with dot (.), Exclamation mark (!) or Question mark (?).

Listing 27. modifierExamples.php

  <?php
  require '../libs/Smarty.class.php';
  $smarty = new Smarty();
  $smarty->assign('sen', 'I am eating Rio biscuit at the Moment. Wow! Do you wanna eat?');
  $smarty->display('modifierExamples.tpl');
  ?>
  

Listing 28. modifierExamples.tpl

  Text : {$sen}<br>
  No. of Sentences: {$sen|count_sentences} 
  

Here is the output:

Figure 15. Count_ sentences modifier example in Smarty

count_paragraphs

The count_sentences[%2] modifier counts the total number of paragraphs present in a variable.

Listing 29. modifierExamples.php

  <?php
  require '../libs/Smarty.class.php';
  $smarty = new Smarty();
  $smarty->assign('par', "Too much working results in depression. \n\n
  Keep youself Smart and Healthy.\n\n
  Moral: Health is Wealth. ");
  $smarty->display('modifierExamples.tpl');
  ?>
  

Listing 30. modifierExamples.tpl

  Text : {$par|nl2br}<br><br>
  No. of Paragraphs: {$par|count_paragraphs}<br><br> 
  

Follow the below output for clear understanding:

Figure 16. Count_ paragraphs modifier example in Smarty

indent

The indent modifier is used to place spaces in the beginning of every line. By default, four spaces are placed, but if you want to place additional or more spaces, then provide additional parameter value after indent modifier. The following example will make it easy to understand.

Listing 31. modifierExamples.php

  <?php
  require '../libs/Smarty.class.php';
  $smarty = new Smarty();
   $smarty->assign('quotes', 
  'Open the door of your treasure today, for tomorrow the key will not be in your hands.');
  $smarty->display('modifierExamples.tpl');
  ?>
  

Listing 32. modifierExamples.tpl

  {$quotes}<br><br>
  {$quotes|indent}<br><br>
  {$quotes|indent:9} 
  

Here is the output for the above example:

Figure 17. Indent modifier example in Smarty

.replace

The replace modifier is used to replace the match value present in a variable.

Listing 33. modifierExamples.php

  <?php
  require '../libs/Smarty.class.php';
  $smarty = new Smarty();
  $smarty->assign('repl', "Real Madrid is a good Soccer Team.");
  $smarty->display('modifierExamples.tpl');
  ?>
  

Listing 34. modifierExamples.tpl

  Original Text:<br> {$repl}<br><br>
  After replace:<br>{$repl|replace:'a good':'the best'}<br><br> 
  

The output for the above program is illustrated below:

Figure 18. Replace modifier example in Smarty

.truncate

The truncate modifier truncates or shortens variable content to a specific character length. If a specific character length is not provided, then the default value is 80; means it will display up to 80 characters, if present in a variable. There are a lot of ways you can truncate the value of variable. If you want to truncate a variable to a specific character length, then specify an additional string parameter after 'truncate' modifier by placing colon (:). You can further modify the truncate modifier by displaying a specific symbol when the variable is truncated, e.g. "...", "---", " ", "___",etc. Next, if you want to finish the variable value at fixed length of character, then provide the third parameter of truncate modifier and set it as 'TRUE'.

Let's conclude the truncate discussion with the following example to make the concept clearer.

Listing 35. modifierExamples.php

  <?php
  require '../libs/Smarty.class.php';
  $smarty = new Smarty();
  $smarty->assign('trun','Eating and sleeping is the creed animals; to adopt it is the manner of                           fools.');
  $smarty->display('modifierExamples.tpl');
  ?>
  

Listing 36. modifierExamples.tpl

  {$trun}<br><br> 
  {$trun|truncate}<br><br>
  {$trun|truncate:25}<br><br>
  {$trun|truncate:35:'...":true}<br><br> 
  {$trun|truncate:20:"****":true}<br><br>
  {$trun|truncate:10:' ':true:true} 
  

Below is the ouput for the tuncate modifier example:

Figure 19. Truncate modifier example in Smarty

Conclusion

In this article, I have first provided a brief introduction to the Smarty template used for developing any website with quite ease. Then I stated the different features of Smarty template and reasons for choosing Smarty template for developing and designing websites. Next, I illustrated the installation procedure of Smarty template. Furthermore, I explained the syntax of Smarty template and finally provide the different operation, methods etc. for using them in your Smarty project to make your project surprisingly best. Stay tuned for my next tutorial in which I will be going for advanced features and database-based contents in Smarty template.

Links

http://www.smarty.net

http://www.smarty.net/download



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