Search code examples
phptemplatestwigtemplate-engine

PHP Twig starter Problems (doesn't find templates)


My google foo as at its limits :/. I hope you can help me. Twig can't find my templates and I iterated through a lot of random internet finds :D.

It works, when I visit the index.php (uncomment the last line), but it doesn't when I visit webserver.tld/control/xyz/sitename.php.

Following structure:

  • ./index.php
  • ./lib/Twig/{Twig stuff}
  • ./control/xyz/{sitename.php, other files...}
  • ./templates/categoryA/{sitename.phtml, other files...}

index.php

require_once 'lib/Twig/Autoloader.php';
Twig_Autoloader::register();
$template_dir = 'templates/categoryA';
$loader = new Twig_Loader_Filesystem($template_dir);
$twig = new Twig_Environment($loader, array('debug' => true,));
// echo $twig->render('sitename.phtml', array('name' => 'Rapunzel'));

/control/xyz/sitename.php

require_once '../../index.php';
$template = $twig->loadTemplate($template_dir . '/sitename.phtml');
echo $template->render(array('name' => 'Rapunzel'));

The Error message

Uncaught exception 'Twig_Error_Loader' with message 'The "templates/categoryA" directory does not exist.' in /asdf/asdf/TEST_twig/lib/Twig/Loader/Filesystem.php on line 94

What I've tried

I tried to load several templates via an array (as argument of the Twig_Loader_Filesystem) and additionally I tried $loader->addPath() without success :/.


Solution

  • I don't know, why it didn't work earlier. My "solution" now works. But it might not be a good one :D.

    index.php

    require_once 'lib/Twig/Autoloader.php';
    Twig_Autoloader::register();
    $template_dir = (
        __DIR__.'/templates/categoryA',
        __DIR__.'/templates'
    );
    $loader = new Twig_Loader_Filesystem($template_dir);
    $twig = new Twig_Environment($loader, array('debug' => true,));
    

    sitename.php

    require_once '../../index.php';
    $template = $twig->loadTemplate('sitename.phtml');
    echo $template->render(array('name' => 'Rapunzel'));