1,105,534 Community Members

Basic Smarty templating

Member Avatar
(pritaeas)
Reputation Points: 1,420 [?]
Q&As Helped to Solve: 1,835 [?]
Skill Endorsements: 156 [?]
 
2
 

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:

/smarty-demo/
  smarty/
  templates/
    arrayTemplate.tpl
  templates_c/
  cache/
  using-smarty.php

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.

<?php
    // 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
    $smarty->display('arrayTemplate.tpl');
?>



{* arrayTemplate.tpl *}

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

<!doctype html>

{* simple variable substitution *}
<html lang="{$LANGUAGE}">
    <head>
        {* variable substitution using an array with dot notation *}
        <title>{$HEAD.title}</title>
        <meta name="robots" content="{$HEAD.robots}" />
    </head>
    <body>
        <h1>{$BODY.title}</h1>
        <p>{$BODY.text}</p>

        <h2>{$TABLE.title}</h2>
        <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=$TABLE.data 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">
                {else}
                    <tr>
                {/if}
            
                    {* make the list numbered using the counter *}
                    <td>{counter}</td>
                    
                    {* if the publisher is equal to the previous one, don't print it *}
                    {if $PREVIOUS == $BOOK.publisher}
                        <td>&nbsp;</td>
                    {else}
                        <td>{$BOOK.publisher}</td>
                    {/if}
                    
                    <td>{$BOOK.isbn}</td>
                    
                    {* trim the title to 40 characters and add dots *}
                    <td>{$BOOK.title|truncate:30:"...":true}</td>
                </tr>
                
                {* remember the publisher *}
                {assign var=PREVIOUS value=$BOOK.publisher} 

            {foreachelse}
                {* this is executed when the array is empty *}
                <tr>
                    <td>No information found.</td>
                </tr>
            {/foreach}
        </table>
        <p>
            {* show the date, use the date_format modifier to format *}
            Generated at:
            {$smarty.now|date_format:' %Y-%m-%d %H:%M:%S'}
        </p>
    </body>
</html>
{/strip}
Member Avatar
iamthwee
Posting Sage
7,067 posts since Aug 2005
Reputation Points: 1,307 [?]
Q&As Helped to Solve: 595 [?]
Skill Endorsements: 74 [?]
Featured
 
0
 

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

LastMitch
Deleted Member
 
11
 

@pritaeas

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.

Member Avatar
pritaeas
mod_pritaeas
11,315 posts since Jul 2006
Reputation Points: 1,420 [?]
Q&As Helped to Solve: 1,835 [?]
Skill Endorsements: 156 [?]
Moderator
Featured
Sponsor
 
1
 

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.

Member Avatar
pritaeas
mod_pritaeas
11,315 posts since Jul 2006
Reputation Points: 1,420 [?]
Q&As Helped to Solve: 1,835 [?]
Skill Endorsements: 156 [?]
Moderator
Featured
Sponsor
 
1
 

Updated the template (lines 76/77).

You
Post:
Start New Discussion
View similar articles that have also been tagged: