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?

Sunderam Dubey
  • 1
  • 11
  • 20
  • 40
Sumithran
  • 6,217
  • 4
  • 40
  • 54

2 Answers2

4

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.

Caconde
  • 4,177
  • 7
  • 35
  • 32
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
Nicolai Fröhlich
  • 51,330
  • 11
  • 126
  • 130