jAC jAC - 9 months ago 72
Twig Question

How to register a twig extension in php

I am currently using twig standalone (not with symphony or composer) and am not finding in the documentation on how to register an extension in php.

My index.php file looks like this


require_once 'Twig/Autoloader.php';

$loader = new Twig_Loader_Filesystem('views');
$twig = new Twig_Environment($loader);
$twig->addExtension(new Test_Twig_Extension())
echo $twig->render('index.twig');

My extension class looks like this (ext.php)


class Twig_Extension_Test extends Twig_Extension {

public function getFunctions() {
return array(
new Twig_SimpleFunction('my_function', array($this,'my_function'))

public function my_function($arg1, $arg2) {
echo "Arg1: {$arg1} and Arg2: {$arg2}";

public function getName(){
return 'Test';


I get the following error:

Fatal error:
Interface 'Twig_ExtensionInterface' not found in
C:\xampp\htdocs\Twig\Extension.php on line 12

I have found tones of articles with setting it up with yaml but I am not using yaml.

I am sure I am not registering this properly or do not have something set up just right.

Any help is appreciated.

EDIT: Above code is now corrected to match the solution.

Answer Source

So what I figured out is is the following:

  1. When autoloading you do not need to require/include the class file

  2. The name of your extension should start with Twig_Extension_ (for example i had to rename mine to Twig_Extension_Test rather than Test_Twig_Extension like the docs some time show)

  3. Make sure your Twig_Extension_Test class has the getName method in it.

  4. Name your extension file to be last part of class name. So mine had to be called Test.php. I believe this is case sensative as well.

  5. Place this file into the Twig/Extension/ folder

  6. Call $twig->addExtension(new Twig_Extension_Text());

I have updated my code in the Question to reflect these steps