Page 1 of 1

An Introduction to Smarty PHP Template Engine Rate Topic: ***** 1 Votes

#1 codeprada  Icon User is offline

  • Changed Man With Different Priorities
  • member icon

Reputation: 946
  • View blog
  • Posts: 2,355
  • Joined: 15-February 11

Post icon  Posted 13 November 2011 - 08:32 PM

*
POPULAR

Introduction
Smarty is a template engine that allows developers to easily separate their HTML and CSS from their PHP. It also provides added functionality such as date formatting and cycling through values. It's caching capabilities are extremely flexible and useful in increasing performance and lowering bandwidth usage. From personal experience Smarty can decrease development time up to 40% by greatly reducing the amount of code you must write. It also makes it easier to organize your files and maintain a standard layout throughout your website.

Installation
The engine can be downloaded here. Installing it is as easy as extracting the files into a directory within your website and including the file Smarty.class.php. SmartyBC.class.php is used if you need backward compatibility with earlier versions of Smarty.

Getting Started With Configurations
Organizing your directories is very important and will benefit you in the long run. Above your public directory (usually public_html) create a directory called private and within that four (4) directories with the following names:
  • classes - Holds our classes and makes it easier to autoload them
  • compiledir - Holds Smarty's compiled templates
  • templates - Holds our template files
  • cache - Holds the cache files created by Smarty

Next move your Smarty files into the classes directory. Finally in the root directory of your private directory create a file named config.php.
Here's a visual of our directory layout so far.

Attached Image

Our config.php file will store the absolute paths of each of our major directories. This way if you must relocate a directory you won't have to edit multiple files.
Within our config.php file we will also register an autoload function for our classes. So basically this is our config.php file.
<?php
    //Define directories
    define('DS', DIRECTORY_SEPARATOR);
    define('DIRECTORY_TEMPLATES', 	dirname(__FILE__) . DS . 'templates' . DS);
    define('DIRECTORY_CACHE', 		dirname(__FILE__) . DS . 'cache' . DS);
    define('DIRECTORY_COMPILEDIR',	dirname(__FILE__) . DS . 'compiledir' . DS);
    define('DIRECTORY_CLASSES',		dirname(__FILE__) . DS . 'classes' . DS);
    //end
	
    //autoloader function
    function autoload($class_name)
    {
        if(file_exists(DIRECTORY_CLASSES . $class_name . '.class.php'))
        {
            require_once DIRECTORY_CLASSES . $class_name . '.class.php';
        }
    }
    //register function
    spl_autoload_register('autoload');	
?>



Creating Templates
In your templates directory create two files: layout.tpl, index.tpl. The layout template will hold the layout of each page and our index template will hold the body of the index page.

In your layout.tpl file add this
<!DOCTYPE html>
<html>
<head>
    <title>Smarty PHP Template Engine</title>
</head>
<body>
    <!-- Body block -->
    {block name=body}{/block}
</body>
</html>



And your index.tpl file
{block name=body}
	<h1>Smarty Tutorial</h1>
    <p>Smarty can extend templates as deep as you so desire. Anything outside of this block tag will not be displayed!</p>
{/block}
<p>This text will not be displayed because it does not fall within the body block</p>



In the layout.tpl file you'll see that we have a block tag named body. This acts as a placeholder the body. Any template that extends layout.tpl must have a block tag with named body. That was also demonstrated in our index.tpl file. Anything outside of this block tag will not be parsed or in other words dropped.

Assigning Values to Template Variables
The previous example showed us how to display pages using a layout and extending it but the pages are static. What if we wanted to change the content? Smarty's solution is template variables which can be assigned values. Change the content of your index.tpl file to the following:
{block name=body}
    <h1>{$heading}</h1>
    <p>{$paragraph}</p>
{/block}


A template variable is surrounded with curly braces and starts with a dollar sign ($). As you may have seen the template variables here are heading and paragraph. Now to assign values we must go into our index.php file.
<?php
    //must be included in every script
    require_once '../private/config.php';
	
    //Set the directories
    $smarty = new Smarty;
    $smarty->setTemplateDir(DIRECTORY_TEMPLATES);
    $smarty->setCacheDir(DIRECTORY_CACHE);
    $smarty->setCompileDir(DIRECTORY_COMPILEDIR);
    //end
	
    //Assign values to template variables
    $smarty->assign('heading', 'Welcome to a Smarty Tutorial!');
    $smarty->assign('paragraph', 'Congratulations if you have reached this far.');
    //end
	
    //display our page
    $smarty->display('extends:layout.tpl|index.tpl');
?>


To assign values to these variables you must use the assign function.

Handling Loops
Smarty can also handle arrays using various methods. Here are a few


Sections are quite easy to use once you understand the basics. Here's an example of creating a SELECT element using section. Update your index.tpl file with the following:
{block name=body}
    <h1>{$heading}</h1>
    <p>{$paragraph}</p>
    <div>
    <select>
    	{section name=number loop=$array}
        	<option>{$array[number]}</option>
        {/section}
    </select>
    </div>
{/block}


A section requires a name which will be used as the index of the current element and also a loop which is as you guessed the array to be iterated. A section can only work with numerically indexed arrays. They can also be nested as deep as you desire. Now you must update your index.php file by adding the following line of code with the other assignments.
$smarty->assign('array', range(1, 20));


You must always perform an assignment before displaying a template. Now run your index.php file and you should see the results.

Foreach is a more powerful version of section. It can handle both numerical and associative arrays. From personal experience it works perfectly with multidimensional associative arrays such as those from mysqli_result::fetch_all and PDOStatement->fetchAll.

Let's create a multidimensional array and assign it to a template variable named result.
$result = array(
	0 => array(
		'id' => 222,
		'name' => 'codeprada'
	),
	1 => array(
		'id' => 333,
		'name' => 'Jessica'
	),
	2 => array(
		'id' => 444,
		'name' => 'Carlos'
	)
);
$smarty->assign('result', $result);



In your index.tpl file add the following
<select>
    {foreach $result as $row}
        <option value="{$row.id}">{$row.name}</option>
    {/foreach}
</select>


Here we see our $result variable used in the foreach loop as the array and the values represented as $row. Since it is a multidimensional array $row will be an array also. To access an element of an array in Smarty the dot (.) operator is used.

Conditional Statements
Smarty allows for conditional statements using {if},{elseif},{else}. It also supports a high level syntax for instance {if $number is not even} ... {/if}.

Suppose in our example we wanted to select Jessica as the default value in our SELECT element. We would need to add the selected boolean attribute to that particular option.
{block name=body}
    <h1>{$heading}</h1>
    <p>{$paragraph}</p>
    <div>
    <select>
        {foreach $result as $row}
            <option {if $row.id == 333}selected{/if} value="{$row.id}">{$row.name}</option>
        {/foreach}
    </select>
    </div>
{/block}


As you see above an IF clause is added which checks for the ID 333. This is hardly a real world example. Let's try something a bit more practical. What if you wanted to select the value that was passed from $_GET['id'] (basically anything dynamic)?
{block name=body}
    <h1>{$heading}</h1>
    <p>{$paragraph}</p>
    <div>
    <select>
        {foreach $result as $row}
            <option {if $row.id == $smarty.get.id}selected{/if} value="{$row.id}">{$row.name}</option>
        {/foreach}
    </select>
    </div>
{/block}


Another great feature of Smarty is that it can grab values directly from superglobal arrays such as:
  • $_SESSION
  • $_COOKIE
  • $_GET
  • $_POST
  • $_SERVER
  • $_REQUEST
  • $_ENV


It doesn't stop there. Smarty can also read constants directly with the syntax $smarty.const.CONSTANT_NAME. I'm sure by now you've realized we've done the same amount of work in a lot less lines of code and development time.

Escaping Smarty Delimiters
There will be times when you need to use the curly braces for something else other than enclosing a template variable. There are two ways in which you can achieve this without causing Smarty to output an error. They are by using one of the following Smarty function:


Here's an example of each:
{ldelim},{rdelim}
{block name=body}
    <h1>{$heading}</h1>
    <p>{$paragraph}</p>
    <div>
    <select id="names">
        {foreach $result as $row}
            <option value="{$row.id}">{$row.name}</option>
        {/foreach}
    </select>
    <script type="text/javascript">
		document.getElementById('names').addEventListener('change', function(){ldelim}
			alert(this.value);
		{rdelim}, false);
	</script>
    </div>
{/block}



{literal}{/literal}
{block name=body}
    <h1>{$heading}</h1>
    <p>{$paragraph}</p>
    <div>
    <select id="names">
        {foreach $result as $row}
            <option value="{$row.id}">{$row.name}</option>
        {/foreach}
    </select>
    {literal}
    <script type="text/javascript">
		document.getElementById('names').addEventListener('change', function(){
			alert(this.value);
		}, false);
	</script>
    {/literal}
    </div>
{/block}



I will be sure to discuss more advance topics in the near future.

Is This A Good Question/Topic? 8
  • +

Replies To: An Introduction to Smarty PHP Template Engine

#2 MATTtheSEAHAWK  Icon User is offline

  • D.I.C Addict
  • member icon

Reputation: 137
  • View blog
  • Posts: 782
  • Joined: 11-September 10

Posted 14 November 2011 - 05:12 AM

Wonderful tutorial! I didn't read it all but I will refer back to this later. I work at my father's clothing store and they're totally redoing their website to put an e-commerce engine on there (x-cart) and I'm working on a fair amount of dev work on it, just getting it ready, editing some important things, helping when help is needed. X-cart uses smarty and when I first saw it I was like "what is this crap?" but then I got used to it and it's actually really great.

Again, wonderful tutorial!
Was This Post Helpful? 0
  • +
  • -

#3 Jstall  Icon User is offline

  • Lurker
  • member icon

Reputation: 434
  • View blog
  • Posts: 1,042
  • Joined: 08-March 09

Posted 14 November 2011 - 05:57 AM

Great tutorial codeprada , I use Smarty frequently but didn't know that it could access super globals, nicely done :)
Was This Post Helpful? 0
  • +
  • -

#4 codeprada  Icon User is offline

  • Changed Man With Different Priorities
  • member icon

Reputation: 946
  • View blog
  • Posts: 2,355
  • Joined: 15-February 11

Posted 14 November 2011 - 06:15 AM

Thanks, glad you guys like it. :)

My attachment didn't show sadly but here it is
Attached Image

This post has been edited by codeprada: 14 November 2011 - 06:16 AM

Was This Post Helpful? 1
  • +
  • -

#5 EnvXOwner  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 357
  • View blog
  • Posts: 2,319
  • Joined: 10-August 09

Posted 14 November 2011 - 06:28 AM

Nicely done :)
Was This Post Helpful? 0
  • +
  • -

#6 Atli  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 3717
  • View blog
  • Posts: 5,981
  • Joined: 08-June 10

Posted 14 November 2011 - 06:33 AM

View Postcodeprada, on 14 November 2011 - 01:15 PM, said:

My attachment didn't show sadly but here it is

Fixed that for you ;)

Very nice article by the way. I use Smarty a lot but I wasn't aware of the 'extends:layout.tpl|index.tpl' way of injecting templates into other templates. I've just been using include statements in the templates themselves. This is much better! :)
Was This Post Helpful? 1
  • +
  • -

#7 codeprada  Icon User is offline

  • Changed Man With Different Priorities
  • member icon

Reputation: 946
  • View blog
  • Posts: 2,355
  • Joined: 15-February 11

Posted 14 November 2011 - 06:36 AM

Thanks Atli.

Didn't know Smarty was that popular on here either.
Was This Post Helpful? 1
  • +
  • -

#8 kevsy  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 4
  • Joined: 24-August 10

Posted 02 November 2013 - 12:43 PM

testdomain.local\public\index.php

line 6.

$smarty = new Smarty;


I've hit a bit of a bad patch. All that returns from my code is:

Fatal:error Class Smarty not found in C:\wamp\www\testdomain.local\public\index.php on line 6

All the code looks fine and doesn't show errors. I suspect my path is up the shoot...
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1