dongzhan5246 2016-11-01 16:03
浏览 95
已采纳

如何在PHP中注册twig扩展

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

<?php
include 'exts/ext.php';
require_once 'Twig/Autoloader.php';
Twig_Autoloader::register();

$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)

<?php
//require_once 'Twig/Extension.php';
//require_once 'Twig/ExtensionInterface.php';
class Test_Twig_Extension 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 'my_function';
}

}
?>

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.

  • 写回答

1条回答 默认 最新

  • dongyan9838 2016-11-01 18:25
    关注

    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

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器