如何在模板引擎TWIG中从全路径加载模板


How to load a template from full path in the template engine TWIG

我想知道如何从它的完整路径加载模板(如FILE constant 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方法。

我该怎么办?

我不想为这样的东西创建自己的加载器。

谢谢

就这么做:

$loader = new Twig_Loader_Filesystem('/');

这样->loadTemplate()将加载相对于/的模板。

或者,如果你想同时使用相对路径和绝对路径加载模板:

$loader = new Twig_Loader_Filesystem(array('/', '/path/to/templates'));

下面是加载给定的绝对(或非)路径的加载器:

<?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));
        }
    }
}
?>

扩展加载器优于修改库:

<?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);
    }
} 

这适用于我(Twig 1.x):

final class UtilTwig
{
    /**
     * @param string $pathAbsTwig
     * @param array $vars
     * @return string
     * @throws 'Twig'Error'LoaderError
     * @throws 'Twig'Error'RuntimeError
     * @throws 'Twig'Error'SyntaxError
     */
    public static function renderTemplate(string $pathAbsTwig, array $vars)
    {
        $loader = new Twig_Loader_Filesystem([''], '/');
        $twig = new Twig_Environment($loader);
        $template = $twig->loadTemplate($pathAbsTwig);
        $mailBodyHtml = $template->render($vars);
        return $mailBodyHtml;
    }
}

用法:

$htmlBody = UtilTwig::renderTemplate('/absolute/path/to/template.html.twig', [
    'some' => 'var', 
    'foo' => 'bar'
]);

在Symfony的(版本5.4)配置添加新的核心路径文件夹与您的模板

twig:
    default_path: '%kernel.project_dir%/templates'
    paths:
        '%kernel.project_dir%/src/Service/SendEmail/EmailTpl': EmailTpl

现在可以渲染模板了。

在控制器:

$this->render('@EmailTpl/bobo_reg.html.twig')

在其他地方:

$content = $this->container->get('twig')->render('@EmailTpl/bobo_reg.html.twig');