0

I am writing code for a view within a customer component and need to bring in a subtemplate based on a parameter passed to the code. If a parameter, $p exists, and the corresponding template can be found, I need my code load it. Otherwise, it needs to load a default template.

I can technically achieve what I am trying to do with the following code, but I don't like the idea of using an exception handler to determine if the template file exists. Is there a joomla method that can first check to see if the template that corresponds to $p exists?

try {
    echo $this->loadTemplate($p);   
} catch(exception $ex) {
    echo $this->loadTemplate("default");
}
TMorgan
  • 655
  • 1
  • 7
  • 13

1 Answers1

0

Sure, $p is just a string defining the name of the sub-template file. You could calculate the path to the file $p is referencing and check if it's available — but that's a bit redundant given that loadTemplate() does this (while also checking for template overrides and alternate layouts).

If you have a look at the comments for the loadTemplate() you will see that it throws an exception on error, so if you have a fall back strategy then you should catch the exception and implement it. So, your approach would appear to be the correct way.

/**
 * Load a template file -- first look in the templates folder for an override
 *
 * @param   string  $tpl  The name of the template source file; automatically searches the template paths and compiles as needed.
 *
 * @return  string  The output of the the template script.
 *
 * @since   12.2
 * @throws  Exception
 */
public function loadTemplate($tpl = null)
{
Craig
  • 9,335
  • 2
  • 34
  • 38
  • Thanks. I have been taught to avoid relying on exception handlers for scenarios that fall within the normal program flow. But, in this case, it would probably be better to rely on loadTemplate's built in template locator, than to reinvent the wheel with a template locator of my own. I just wanted to make sure there weren't any "better" ways of doing it. – TMorgan Nov 26 '13 at 15:31