How to Smartify Your Output
Let's cover basic use of Smarty for s9y developers. We'll be using a hypothetical plugin that produces an archive of webcomics for you.
Step 1: Decide what kind of data you need to create decent output. In our example, that's probably a list of comics, each of which has a title, an image, a number, a date, and a transcript.
Step 2: Place all that data in an array with descriptive keys. We'd probably be creating an array of arrays, something like this:
Code: Select all
$archive = array();
foreach ($comic as $allcomics) {
$archive[] = array('img' => $comic['image], 'title' => $comic['title'], 'number' => $comic['index'], 'date' => $comic['published_on'], 'transcript' => $comic['script']);
}
Step 3: Assign the array to Smarty using a descriptive name.
Code: Select all
$serendipity['smarty']->assign('comic_archive', $archive);
Step 4: Create a default template to use this output. In Smarty, we'll want to iterate over each entry, printing it appropriately:
Code: Select all
{foreach from=$comic_archive item='comic'}
<h3>{$comic.title}</h3>
<p><span class="date">{$comic.date'}</span> #{$comic.number}</p>
<img src="{$comic.img}">
{/foreach}
You don't have to use all the stuff you put in the array. But for a default template, it's a good idea, just so future modders know what's available.
Step 5: Find the template file. When you're ready to actually print your template, call:
Code: Select all
$tpl = serendipity_getTemplateFile('mytemplate.tpl');
This will either return the path to the template file as defined in the current template, or empty, or the plain name of the template. You can use file_exists() to see if a valid template was returned, and default to a known working template if it isn't.
Step 6: Call Smarty to produce the output.
Code: Select all
$html = serendipity_smarty_fetch('UNIQUE_NAME', 'mytemplate.tpl', false);
print $html;
If you pass 'true' instead of 'false', the output will be directly printed. Additionally, the output is assigned to {$UNIQUE_NAME} in Smarty, in case you want to get at it again later. Serendipity will call serendipity_getTemplatFile on 'mytemplate.tpl' again; if you passed a full file name (like a default from Step 5), it
should work.
And that's all there is to it! If we find errors in this, I'll be editing the post to correct them.