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

如何在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 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?