0

我目前正在使用独立的 twig(不使用 symphony 或 composer),并且在文档中没有找到关于如何在 php 中注册扩展的文档。

我的 index.php 文件看起来像这样

<?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');
?>

我的扩展类看起来像这样(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';
}

}
?>

我收到以下错误:

致命错误:在第 12 行的 C:\xampp\htdocs\Twig\Extension.php 中找不到接口“Twig_ExtensionInterface”

我发现了很多用 yaml 设置它的文章,但我没有使用 yaml。

我确定我没有正确注册或没有正确设置。

4

1 回答 1

1

所以我想出的是以下内容:

  1. 自动加载时,您不需要/包含类文件

  2. 您的扩展名应该以Twig_Extension_ 开头(例如,我不得不将我的名称重命名为 Twig_Extension_Test 而不是 Test_Twig_Extension 就像文档有时显示的那样)

  3. 确保您的 Twig_Extension_Test 类中有 getName 方法。

  4. 将您的扩展文件命名为类名的最后一部分。所以我的必须被称为Test.php。我相信这也是区分大小写的。

  5. 将此文件放入 Twig/Extension/ 文件夹

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

我已经更新了问题中的代码以反映这些步骤

于 2016-11-01T18:25:48.437 回答