Как загрузить шаблон из полного пути в движок шаблонов TWIG - PullRequest
9 голосов
/ 15 августа 2011

Мне интересно, как загрузить шаблон из его полного пути (например, FILE константа give).

На самом деле вы должны установить «корневой» путь для шаблона следующим образом:

require_once '/path/to/lib/Twig/Autoloader.php';
Twig_Autoloader::register();

$loader = new Twig_Loader_Filesystem('/path/to/templates');
$twig = new Twig_Environment($loader, array(
   'cache' => '/path/to/compilation_cache',
));

А затем:

$template = $twig->loadTemplate('index.html');
echo $template->render(array('the' => 'variables', 'go' => 'here'));

Я хочу вызвать метод loadTemplate с полным путем, а не только с именем файла.

Как можноя делаю?

Я не хочу создавать собственный загрузчик для таких вещей ..

Спасибо

Ответы [ 3 ]

8 голосов
/ 15 августа 2011

Просто сделайте это:

$loader = new Twig_Loader_Filesystem('/');

Так что -> loadTemplate () загрузит шаблоны относительно /.

Или если вы хотите иметь возможность загружать шаблоны как сотносительный и абсолютный путь:

$loader = new Twig_Loader_Filesystem(array('/', '/path/to/templates'));
4 голосов
/ 28 ноября 2013

Расширить загрузчик лучше, чем изменить библиотеку:

<?php

/**
 * Twig_Loader_File
 */
class Twig_Loader_File extends Twig_Loader_Filesystem
{
    protected function findTemplate($name)
    {
        if(isset($this->cache[$name])) {
            return $this->cache[$name];
        }

        if(is_file($name)) {
            $this->cache[$name] = $name;
            return $name;
        }

        return parent::findTemplate($name);
    }
} 
4 голосов
/ 16 августа 2011

Вот загрузчик, который загружает заданный абсолютный (или нет) путь:

<?php


class TwigLoaderAdapter implements Twig_LoaderInterface
{
    protected $paths;
    protected $cache;

    public function __construct()
    {

    }

    public function getSource($name)
    {
        return file_get_contents($this->findTemplate($name));
    }

    public function getCacheKey($name)
    {
        return $this->findTemplate($name);
    }

    public function isFresh($name, $time)
    {
        return filemtime($this->findTemplate($name)) < $time;
    }

    protected function findTemplate($path)
    {
        if(is_file($path)) {
            if (isset($this->cache[$path])) {
                return $this->cache[$path];
            }
            else {
                return $this->cache[$path] = $path;
            }
        }
        else {
            throw new Twig_Error_Loader(sprintf('Unable to find template "%s".', $path));
        }
    }

}

?>
...