PHP, Smarty: checking a template in different folders

for our last project, we used Django, where you can specify a list of folders that are looking for a template, say, with a name example.html. Now we are back to Smarty (PHP) and are wondering if there is anything like that.

Smarty version: may be advanced.

Behavior:

  • Smarty feed with an array of folders.
  • Call a pattern with $smarty->display()or {include}.
  • Smarty searches the folders and accepts the first template matching the name.

I looked at Smarty resources , but they look like an excess for this task, and documents are a bit rare in this thread. Any ideas how to do this?

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

Greetings

+3
source share
4 answers

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']default is $this->template_dirc Smarty::_fetch_resource_info().

So it looks like you can install $smarty->template_dirinto an array of directories to look. Please note that this will not be recursive. This should be an undocumented function.

+4
source

, , , Smarty, , , , OP. .

, , /ext/templates. , /base/templates. , .

class View extends Smarty {
    function __construct() {
        parent::Smarty();

        $this->template_dir = LOCAL_APP_ROOT.'/ext/templates';
        $this->compile_dir = LOCAL_APP_ROOT.'/cache/compile';

        $this->default_template_handler_func = '__default_template_handler';
    }
}


function __default_template_handler($resource_type, $resource_name, &$template_source, &$template_timestamp, &$smarty_obj) {
    if ($resource_type == 'file') {
        if (!is_readable($resource_name)) {
            $defaultPath = LOCAL_APP_ROOT."/base/templates/$resource_name";
            if (file_exists($defaultPath)) {
                $template_source = file_get_contents($defaultPath);
                $template_timestamp = filemtime($defaultPath);
                return true;
            }
        }
    }
    return false;
}
+2

Smarty template_dir . Smarty , .

+1

, Smarty ( template_dir Smarty). , , , .

0

Source: https://habr.com/ru/post/1713752/


All Articles