I am currently using v1.12.2 Twig as a standalone templating engine.
I wrote a Twig extension called Utility_Twig_Extension in a file called UtilityExtension.php
and an index.php
//index.php
require_once '../vendor/twig/twig/lib/Twig/Autoloader.php';
Twig_Autoloader::register();
$loader = new Twig_Loader_Filesystem(OEBPS);
$twig = new Twig_Environment($loader, array(
'cache' => APP . DS . 'cache',
));
require_once '../vendor/twig/twig/ext/utility/UtilityExtension.php';
$twig->addExtension(new Utility_Twig_Extension());
Here is the UtilityExtension.php //UtilityExtension.php namespace UtilityTwigExtension;
class Utility_Twig_Extension extends Twig_Extension
{
public function getName()
{
return "utility";
}
}
Here is my directory structure:
src
|__app
| |__ index.php
|__vendor
|__twig
|__twig
|__ext
|__lib
I cannot even load the file properly.
I have traced the issue to the fact that the extension class tries to extend Twig_Extension.php.
So I require_once
the Twig_Extension which is the Extension.php file in UtilityExtension.php. However, still not working.
Most documentation talks about adding a custom Twig Extension in the context of Symfony.
I am using Twig standalone, so I have yet to find any documentation on that.
Please advise.
UPDATE1:
By not working, I meant that I get the 500 server error. I ran error_reporting(E_ALL) was to no avail.
The error was relieved the moment I removed the words extends Twig_Extension
from the extension class.
UPDATE2:
I realized it was a namespace issue. because I removed the namespace UtilityTwigExtension;
from the UtilityExtension.php and the server 500 error was gone.
So I put the namespace UtilityTwigExtension;
back and then call
require_once '../vendor/twig/twig/ext/utility/UtilityExtension.php';
$twig->addExtension(new UtilityTwigExtension\Utility_Twig_Extension());
the error came back.
Question: How do I call the TwigExtension if I insist on using the namespace? Is there a better way of using namespace?
UPDATE3:
I still get server 500 after trying Luceos answer.
error_reporting(E_ALL);
require_once 'constants.php';
require_once 'ZipLib.php';
require_once '../vendor/twig/twig/lib/Twig/Autoloader.php';
Twig_Autoloader::register();
$loader = new Twig_Loader_Filesystem(OEBPS);
$twig = new Twig_Environment($loader, array(
'cache' => APP . DS . 'cache',
));
require_once '../vendor/twig/twig/ext/utility/UtilityExtension.php';
use UtilityTwigExtension\Utility_Twig_Extension;
$twig->addExtension(new Utility_Twig_Extension());
the UtilityExtension.php
namespace UtilityTwigExtension;
class Utility_Twig_Extension extends Twig_Extension
{
/**
* Returns the name of the extension.
*
* @return string The extension name
*/
public function getName() {
return 'utility';
}
}
namespace UtilityTwigExtension
? Did you create the UtilityTwigExtension in its own namespace? You would then need to add the extension:$twig->addExtension(new UtilityTwigExtension\Utility_Twig_Extension());
– Luceos