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 随身WiFi网络灯亮但是没有网络,如何解决?
  • ¥15 gdf格式的脑电数据如何处理matlab
  • ¥20 重新写的代码替换了之后运行hbuliderx就这样了
  • ¥100 监控抖音用户作品更新可以微信公众号提醒
  • ¥15 UE5 如何可以不渲染HDRIBackdrop背景
  • ¥70 2048小游戏毕设项目
  • ¥20 mysql架构,按照姓名分表
  • ¥15 MATLAB实现区间[a,b]上的Gauss-Legendre积分