neulaender neulaender - 4 months ago 14
Twig Question

PHP Twig Error: Object of class __TwigTemplate_XYZ could not be converted to string

Hey and good morning :).

I'll start with the error message and explain afterwards what I've tried and did:

Catchable fatal error: Object of class __TwigTemplate_[64chars] could not be converted to string in /someFolder/lib/Twig/Loader/Filesystem.php on line 139


The full error message as Image:

The PHP Error Message

The call stack as Text:

Call Stack
# Time Memory Function Location
1 0.0001 123400 {main}( ) ../handleOOP.php:0
2 0.0107 1269656 OOPHandler::runPage( ) ../handleOOP.php:7
3 0.0107 1269768 AnweisungEingeben->stepkontrolle( ) ../OOPHandler.php:62
4 0.0108 1271536 AnweisungEingeben->ausgabe( ) ../AnweisungEingeben.php:77
5 0.0383 1669484 Twig_Environment->render( ) ../AnweisungEingeben.php:442
6 0.0383 1669484 Twig_Environment->loadTemplate( ) ../Environment.php:347
7 0.0383 1669512 Twig_Environment->getTemplateClass( ) ../Environment.php:378
8 0.0384 1669512 Twig_Loader_Filesystem->getCacheKey( ) ../Environment.php:312


In the
AnweisungEingeben.php
I have the following code fragment:

include_once "../lib/Twig/Autoloader.php";
Twig_Autoloader::register();
$template_dirs = array(
$root.'templates/web/anweisungen',
[...]
);
$twig_loader = new Twig_Loader_Filesystem($template_dirs);
$twig = new Twig_Environment($twig_loader, array("debug" => true));
$template = $twig->loadTemplate('Anweisung_Base.phtml');
$wech = $twig->render($template); // line 442 from AnweisungEingeben.php


I already tried:


  • If the paths are correct (via scandir("path"))

  • If Twig gets loaded

  • Minimal Code like

    $loader = new Twig_Loader_Array(array('index.html' => 'Hello World!'));
    $twig = new Twig_Environment($loader);
    echo $twig->render('index.html');



Unfortunately everything results in the same.

The strange thing is, that the exact same code is working flawlessly in a minimal project.

I know it's very chaotic, but the project is existing and growing now for about ~20 years and this twig approach is my try to start(!) separating the logic from the html code.

Answer

You're mixing methods up, you are trying to pass a Twig_Template to the Twig_Environment's render method, while this method actually expect the path to the template as it's first parameter

So either do :

$template = $twig->loadTemplate('Anweisung_Base.phtml');
echo $template->render();

Or

echo $twig->render('Anweisung_Base.phtml');