Basic Smarty templating


This demo will show a PHP script using a Smarty template. It assumes basic installation. In the folder where you copy the script, there should be a smarty folder containing the Smarty files. You should create a writable cache and templates_c folder, and a folder called templates where the .tpl file should be. For example:


The code below shows both files, so make sure you split them. The demo is using arrays and array notation in the template. It is possible to use objects and object notation as well, but I've excluded that here. The template is not using Smarty V3 specifics, so it will be compatible with V2. I hope the comments will provide enough information, if it doesn't, please leave a reply.

LastMitch commented: Thanks! +5
About the Author
    // using-smarty.php

    // prepare some data, a list of books
    // array of arrays as it can be returned from a query (ordered by publisher)
    $arrayData = array (
        array ('isbn' => '0201633612', 'title' => 'Design Patterns: Elements of Reusable Object-Oriented Software', 'publisher' => 'Addison Wesley'),
        array ('isbn' => '0201485672', 'title' => 'Refactoring: Improving the Design of Existing Code', 'publisher' => 'Addison Wesley'),
        array ('isbn' => '0201791692', 'title' => 'SQL Performance Tuning', 'publisher' => 'Addison Wesley'),
        array ('isbn' => '0131429019', 'title' => 'The Art of UNIX Programming', 'publisher' => 'Addison Wesley'),
        array ('isbn' => '0321466756', 'title' => 'Why Software Sucks...and What You Can Do About It', 'publisher' => 'Addison Wesley'),
        array ('isbn' => '143023864X', 'title' => 'Pro HTML5 Programming, Second Edition', 'publisher' => 'Apress'),
        array ('isbn' => '0735619670', 'title' => 'Code Complete: A Practical Handbook of Software Construction, Second Edition', 'publisher' => 'Microsoft Press'),
        array ('isbn' => '0735624003', 'title' => 'Programming Microsoft LINQ (PRO-Developer)', 'publisher' => 'Microsoft Press'),
        array ('isbn' => '190481140X', 'title' => 'Smarty: PHP Template Programming and Applications', 'publisher' => 'Packt Publishing'),
        array ('isbn' => '0130224189', 'title' => 'Algorithms + Data Structures = Programs', 'publisher' => 'Prentice Hall')

    // include the class
    include 'smarty/Smarty.class.php';

    // create a new object
    $smarty = new Smarty();

    // assign a simple string
    // first parameter is what you use in the template
    // second parameter is the value
    $smarty->assign('LANGUAGE', 'en');

    // assign an array
    // in the template you use the dot notation to access it
    $smarty->assign('HEAD', array ('title' => 'Smarty Demo', 'robots' => 'noarchive,nofollow,noindex'));

    // build an array, then assign it
    $title = 'A Simple Smarty Demo';
    $text = 'This will demo some simple ways of using the Smarty templating system.';
    $body = array ('title' => $title, 'text' => $text);
    $smarty->assign('BODY', $body);

    // assign the book information for the table
    $smarty->assign('TABLE', array ('title' => 'List of Books', 'data' => $arrayData));

    // fetch() returns the template result as a string
    $output = $smarty->fetch('arrayTemplate.tpl');

    // display() outputs the template result directly

{* arrayTemplate.tpl *}

{* strip will remove all whitespace, reducing the output *}

<!doctype html>

{* simple variable substitution *}
<html lang="{$LANGUAGE}">
        {* variable substitution using an array with dot notation *}
        <meta name="robots" content="{$HEAD.robots}" />

        <table border="1">
            {* initialize a counter, each call automatically increments it *}
            {counter start=0 print=false}
            {* initialize the PREVIOUS variable *}
            {assign var="PREVIOUS" value=""}

            {* loop the data array, from points to the variable to use *}
            {* item defines the variable inside the loop *}
            {foreach from=$ item=BOOK name=books}
                {* make every third row a different colour *}
                {if $smarty.foreach.books.iteration is div by 3}
                    <tr style="background-color:#eee">
                    {* make the list numbered using the counter *}
                    {* if the publisher is equal to the previous one, don't print it *}
                    {if $PREVIOUS == $BOOK.publisher}
                    {* trim the title to 40 characters and add dots *}
                {* remember the publisher *}
                {assign var=PREVIOUS value=$BOOK.publisher} 

                {* this is executed when the array is empty *}
                    <td>No information found.</td>
            {* show the date, use the date_format modifier to format *}
            Generated at:
            {$|date_format:' %Y-%m-%d %H:%M:%S'}
iamthwee 1,547 Banned Featured Poster

Thanks for this! Will try it out later today if I get a chance.

Member Avatar


I forgot to mention to you couple of months ago. I was a bit busy. When I ran the code this error pop up

on line 91

Undefined index: Previous

Which is this {if $PREVIOUS == $BOOK.publisher}

What I did I just take out the $ and there was no error.

So the example looks good I was pretty happy with the results back then.

But it won't make sense to take it out because it's part of the tutorial.

So I figure out to undo that error without changing much on your tutorial.

If you can change this:

{if $PREVIOUS == $BOOK.publisher}

to this

{if isset($Previous) and $Previous == $BOOK.publisher }

Then there will no error.

I hope you can still adjusted the tutorial so you can make this minor changes.

So from now on when someone test this code there won't be any errors at all.

pritaeas commented: Good spot. +13
pritaeas 2,045 Most Valuable Poster Moderator Featured Poster

There's an easier way. Just add {assign var=PREVIOUS value=""} before the loop. I'll check this when I'm home and update the article above with a comment.

pritaeas 2,045 Most Valuable Poster Moderator Featured Poster

Updated the template (lines 76/77).

LastMitch commented: Thanks for the update. You're right it's much easier +7
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts learning and sharing knowledge.