PhpRiot
Become Zend Certified

Prepare for the ZCE exam using our quizzes (web or iPad/iPhone). More info...


When you're ready get 7.5% off your exam voucher using voucher CJQNOV23 at the Zend Store

Creating Custom Block Tags in Smarty

Implementing the Complete Teaser Block Plug-In

Now that we have a solid understanding of how the block plug-in type works, we can implement a complete plug-in. We will build on the teaser example from earlier in this article.

Our goal is to use the code shown in Listing 7 to generate the output shown in Listing 8.

Listing 7 Sample template code for using the teaser plug-in (listing-7.tpl)
{teaser title='My Article' author='Quentin Zervaas'}
    In this article you will learn about such and such.
{/teaser}

The first thing we will do is to create a Smarty template in which to output the block. We do this to avoid embedding HTML tags within our PHP code, as well as allowing us to easily use other Smarty functionality in our display template as required.

Listing 9 shows the code we write to the teaser.tpl template, which should be saved within the template directory as specified in the template_dir variable. I have just assumed it's in the top-level directory, but you may wish to organise your own templates differently.

Listing 9 The Smarty template used to output the teaser block (teaser.tpl)
<div class="teaser">
    <h3>{$block.title|escape}</h3>
    <div class="byline">By {$block.author|escape}</div>
    <p>
        {$block.content|escape}
    </p>
</div>

Next we implement the teaser plug-in. As you can see in Listing 10, we output values from the $block template variable. This is done to group all block values together without cluttering the Smarty variable namespace.

Listing 10 shows the code for the block.teaser.php file, which we store in the customplugins directory created earlier in this article.

Listing 10 The complete teaser block plug-in (block.teaser.php)
<?php
    function smarty_block_teaser($params, $content, $smarty, $open)
    {
        if ($open) {
            // nothing to do
        }
        else {
            // build the array of template values based
            // on the attributes and block content
            $block = array(
                'title'   => $params['title'],
                'author'  => $params['author'],
                'content' => $content
            );
 
            // assign block values to template
            $smarty->assign('block', $block);
 
            // return template output
            return $smarty->fetch('teaser.tpl');
        }
    }
?>

That is all that's required to implement a block plug-in. You can then call {teaser} {/teaser} in your templates as required (as in Listing 7).

In This Article