smarty_preview

Smarty PHP Template Engine

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:

  • classesHolds our classes and makes it easier to autoload them
  • compiledirHolds Smarty’s compiled templates
  • templatesHolds our template files
  • cacheHolds 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

<!<strong>DOCTYPE</strong> 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><strong>Smarty Tutorial</strong></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 <strong>Smarty Tutorial</strong>!');
    $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=$<strong>array</strong>}
        	<option>{$<strong>array</strong>[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</code><code class="plain">->assign(</code><code class="string">'<strong>array</strong>'</code><code class="plain">, 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 = <strong>array</strong>(
	0 => <strong>array</strong>(
		'id' => 222,
		'name' => 'codeprada'
	),
	1 => <strong>array</strong>(
		'id' => 333,
		'name' => 'Jessica'
	),
	2 => <strong>array</strong>(
		'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.

Related Posts


One thought on “Smarty PHP Template Engine

  1. Flood Restoration Los Angeles l Fire Damage Restoration Los Angeles l Los Angeles Restoration Service l Water damage repair Los Angeles l Restoration Services Los Angeles l Emergency water damage Services Los Angeles

    Thanks a lot for sharing this with all people you actually know what you’re talking about! Bookmarked. Please also talk over with my website =). We can have a link change contract among us

    Reply

Leave a Reply

Your email address will not be published. Required fields are marked *


*