PHP, Smarty: Check for template in different folders

PHPsmartytemplates

for our latest project we used Django, where one can specify a list of folders, that are searched for a template, say, with name example.html. Now, we switched back to Smarty (PHP) and are wondering, if there is something similar.

Smarty version: Can be cutting-edge.

Behaviour:

  1. Feed Smarty with an array of folders.
  2. Call a template either with $smarty->display() or {include}.
  3. Smarty searches through the folders and takes the first template matching the name.

I looked at Smarty resources, but they look like overkill for this task, and the docs are a bit sparse on this topic. Any ideas how this could be done?

An additional problem is, that the list of folders may change depending on the requested URL. Any ideas how to tell Smarty, which compiled template to use?

Cheers,

Best Answer

In Smarty.class.php, in the method Smarty::_parse_resource_name() :

foreach ((array)$params['resource_base_path'] as $_curr_path) {
    $_fullpath = $_curr_path . DIRECTORY_SEPARATOR . $params['resource_name'];
    if (file_exists($_fullpath) && is_file($_fullpath)) {
        $params['resource_name'] = $_fullpath;
        return true;
    }
    // didn't find the file, try include_path
    $_params = array('file_path' => $_fullpath);
    require_once(SMARTY_CORE_DIR . 'core.get_include_path.php');
    if(smarty_core_get_include_path($_params, $this)) {
        $params['resource_name'] = $_params['new_file_path'];
        return true;
    }
}

$params['resource_base_path'] is defaulted to $this->template_dir in Smarty::_fetch_resource_info().

So it looks like you can set $smarty->template_dir to an array of directories to look in. Note that this won't be recursive. This must be an undocumented feature.