Fatal error: Uncaught Error: Class 'Twig_Autoloader' not found
Asked Answered
C

2

5

Recently I installed Twig2.0 via Composer for PHP7.2 and when running the code I'm getting these errors,

( ! ) Fatal error: Uncaught Error: Class 'Twig_Autoloader' not found in C:\wamp64\www\php-twig\example.php on line 4

( ! ) Error: Class 'Twig_Autoloader' not found in C:\wamp64\www\php-twig\example.php on line 4

I go through the issues in GitHub.

Here is my PHP code,

<?php

require 'vendor/autoload.php';
Twig_Autoloader::register();

$loader = new Twig_Loader_Filesystem('templates');

$options = array(
    'name' => 'Sumithran',
);

$twig = new Twig_Environment($loader, $options);

And index.twig

<!DOCTYPE html>

<html>
<head>
    <meta http-equiv="Content-type" content="text/html; charset=utf-8">
    <title>Twig test</title>
</head>
<body>
    
    <h1>Hello world</h1>
    
    <p>And hello {{ name }}</p>
    
</body>
</html>

How to solve this?

Caniff answered 26/8, 2019 at 18:52 Comment(0)
S
5

Twig_Autoloader was deprecated in version 1.21. You are using version 2.0, so you must use:

$loader = new \Twig\Loader\FilesystemLoader('templates');

$options = array(
    'name' => 'Sumithran',
);

$twig = new \Twig\Environment($loader, $options);

More details at Twig Docs - Twig for Developers.

Skydive answered 26/8, 2019 at 20:56 Comment(0)
Z
1

Twig version 2+ introduced the use of namespaces and the class-structure is a bit different now.

For instance instead of in Twig_Loader_Filesystem the filesystem-loader is located at Twig\Loader\FilesystemLoader.

You can also use rector to change all the namespaces to version 2 at once.

Tomas Votruba describes the process more detailed in this blog-post.

TLDR; - Run the following commands to upgrade to namespaces seamlessly.

composer require rector/rector --dev # make sure you have version 0.4.10+ at least
vendor/bin/rector process src --level twig-underscore-to-namespace
Zhdanov answered 26/8, 2019 at 20:56 Comment(1)
If you're using PhpStorm or a similar IDE you can also use autocomplete.Tragacanth

© 2022 - 2024 — McMap. All rights reserved.