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

6

12

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

Barimah answered 15/8, 2011 at 12:31 Comment(0)
L
8

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'));
Lakenyalaker answered 15/8, 2011 at 12:36 Comment(5)
That's not working because i work in local and i have a absolute path like "J:/wamp/www/CHEVAUX/wp-content/plugins/.../index.twig" (i get it from a file const) so it does not accept any char before that path.Barimah
try $loader = new Twig_Loader_Filesystem('J:/');Lakenyalaker
Not working :( The loader do that : "if (is_file($path.'/'.$name)) {.." So i need something like "if (is_file($name)) {.."Barimah
If $path is the root of your filesystem, then $path . '/' . $name == $name (I guess that even on windows, "J:/" . "/some/file" is the same as "J:/some/file". Set $path to whatever is the root of your filesystem on your OS.Lakenyalaker
Yes that would work, but if i move it then it would crash again.. I decided to create a new loader.. I post it below. ThanksBarimah
B
4

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

}

?>
Barimah answered 15/8, 2011 at 23:32 Comment(1)
how do I put this in practice? Do I have to create a new file for that snippet, or how does it work? Sorry I am new to twig and just ran into the exact same problem..Ge
S
4

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);
    }
} 
Slumberous answered 28/11, 2013 at 12:10 Comment(0)
E
1

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'
]);
Entire answered 4/4, 2020 at 9:41 Comment(0)
H
0

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');
Hamill answered 10/2, 2022 at 10:14 Comment(0)
H
0

In Symfony6, you can do :

$this->environment
    ->createTemplate(
        file_get_contents($template),
        $template
     )
     ->render(['some_key' => 'some value']);
Hamid answered 16/3 at 4:42 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.