lithium\template\view\Compiler::template PHP Method

template() public static method

Compiles a template and writes it to a cache file, which is used for inclusion.
public static template ( string $file, array $options = [] ) : string
$file string The full path to the template that will be compiled.
$options array Options for compilation include: - `path`: Path where the compiled template should be written. - `fallback`: Boolean indicating that if the compilation failed for some reason (e.g. `path` is not writable), that the compiled template should still be returned and no exception be thrown.
return string The compiled template.
    public static function template($file, array $options = array())
    {
        $cachePath = Libraries::get(true, 'resources') . '/tmp/cache/templates';
        $defaults = array('path' => $cachePath, 'fallback' => false);
        $options += $defaults;
        $stats = stat($file);
        $oname = basename(dirname($file)) . '_' . basename($file, '.php');
        $oname .= '_' . ($stats['ino'] ?: hash('md5', $file));
        $template = "template_{$oname}_{$stats['mtime']}_{$stats['size']}.php";
        $template = "{$options['path']}/{$template}";
        if (file_exists($template)) {
            return $template;
        }
        $compiled = static::compile(file_get_contents($file));
        if (is_writable($cachePath) && file_put_contents($template, $compiled) !== false) {
            foreach (glob("{$options['path']}/template_{$oname}_*.php", GLOB_NOSORT) as $expired) {
                if ($expired !== $template) {
                    unlink($expired);
                }
            }
            return $template;
        }
        if ($options['fallback']) {
            return $file;
        }
        throw new TemplateException("Could not write compiled template `{$template}` to cache.");
    }

Usage Example

 public function testFallbackWithNonWritableDirectory()
 {
     $this->expectException('/failed to open stream/');
     $result = Compiler::template("{$this->_path}/{$this->_file}", array('path' => LITHIUM_APP_PATH . '/foo', 'fallback' => true));
     $this->assertEqual("{$this->_path}/{$this->_file}", $result);
     $this->expectException('/Could not write compiled template to cache/');
     $this->expectException('/failed to open stream/');
     $result = Compiler::template("{$this->_path}/{$this->_file}", array('path' => LITHIUM_APP_PATH . '/foo', 'fallback' => false));
 }
All Usage Examples Of lithium\template\view\Compiler::template