Matt McDonald’s Website

Accessing Smarty Class Methods in a Template

I was working on a template today, and I needed a way to find out if a smarty template existed or not. If not, I wanted to display a default template. Now, this would be easy if I wanted to check this from the php page, as there is a smarty class method called template_exists(). However, I needed to check this from the template, where no such function exists.

At first I dabbled with accessing the $smarty variable from within the template, because I new the template_dir was in there somewhere. Using that, I could simply use the php function file_exists to check if the template was there. However, I wasn’t sure on the syntax, and concatenating strings within a smarty “if” wasn’t working. I considered writing a plugin to do this check, but why reinvent the wheel? A function already exists to do this, I just needed to get access to it somehow.
Eventually I stumbled on this piece of code:

php code:

$smarty->;register_modifier(‘template_exists’, array(&$smarty, ‘template_exists’));

template code:

{if “reports/sales/$report_type.tpl”|template_exists}
{include file=“reports/sales/$report_type.tpl”}
{else}
{include file=“reports/sales/default.tpl”}
{/if}

Which worked perfectly.

Leave a Reply

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>