如何从模板引擎 TWIG 中的完整路径加载模板

发布于 2024-11-29 18:21:57 字数 614 浏览 4 评论 0原文

我想知道如何从完整路径加载模板(如 FILE 常量给出)。

实际上,您必须为模板设置一个“根”路径,如下所示:

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 方法,而不仅仅是文件名。

我该怎么办?

我不想为这样的事情创建自己的加载程序..

谢谢

I'm wondering how to load a template from it's full path (like FILE constant give).

Actually you have to set a "root" path for template like this :

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',
));

And then :

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

I want to call the loadTemplate method with a full path and not the just the name of the file.

How can i do ?

I don't want to create my own loader for such an thing..

Thanks

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(6

潜移默化 2024-12-06 18:21:57

只需这样做:

$loader = new Twig_Loader_Filesystem('/');

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

或者,如果您希望能够使用相对路径和绝对路径加载模板:

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

Just do that:

$loader = new Twig_Loader_Filesystem('/');

So that ->loadTemplate() will load templates relatively to /.

Or if you want to be able to load templates both with relative and absolute path:

$loader = new Twig_Loader_Filesystem(array('/', '/path/to/templates'));
嘴硬脾气大 2024-12-06 18:21:57

这是一个加载给定绝对(或非)路径的加载器:

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

}

?>

Here is a loader that load an absolute (or not) path given :

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

}

?>
浅浅 2024-12-06 18:21:57

扩展加载器比修改库更好:

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

Extend the loader better than modify the library:

<?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);
    }
} 
一直在等你来 2024-12-06 18:21:57

这对我有用(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'
]);

This works for me (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;
    }
}

Usage:

$htmlBody = UtilTwig::renderTemplate('/absolute/path/to/template.html.twig', [
    'some' => 'var', 
    'foo' => 'bar'
]);
橘和柠 2024-12-06 18:21:57

在 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');

In Symfony's (version 5.4) config add new core path to folder with your templates.

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

Now you can render template.

In controller:

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

In any other place:

$content = $this->container->get('twig')->render('@EmailTpl/bobo_reg.html.twig');
屋顶上的小猫咪 2024-12-06 18:21:57

在 Symfony6 中,你可以这样做:

$this->environment
    ->createTemplate(
        file_get_contents($template),
        $template
     )
     ->render(['some_key' => 'some value']);

In Symfony6, you can do :

$this->environment
    ->createTemplate(
        file_get_contents($template),
        $template
     )
     ->render(['some_key' => 'some value']);
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文