Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/285.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 将所有方法标记为;“安全”;_Php_Twig - Fatal编程技术网

Php 将所有方法标记为;“安全”;

Php 将所有方法标记为;“安全”;,php,twig,Php,Twig,我想创建一个包含HTML助手方法的类: class FormHelper { public function text() { return 'hello <b>world</b>'; } } 然后我可以从Twig调用这些方法: {{ fh.text }} 但是它们总是被转义(例如,hellobworld/b) 我知道我可以用|raw阻止逃逸,但我想用与您相同的方法绕过它 对于类方法,这是可能的吗?Twig Globals只是一个

我想创建一个包含HTML助手方法的类:

class FormHelper {
    public function text() {
        return 'hello <b>world</b>';
    }
}   
然后我可以从Twig调用这些方法:

{{ fh.text }}
但是它们总是被转义(例如,
hellobworld/b

我知道我可以用
|raw
阻止逃逸,但我想用与您相同的方法绕过它


对于类方法,这是可能的吗?

Twig Globals只是一个存储,您可以在其中放置上下文中可用的任何变量。没有应用任何逻辑,就像这些变量存储在本地上下文中一样

但您可以迭代类的方法并将其注册为安全函数:

$object = new FormHelper();
foreach (get_class_methods($object) as $method)
{
    $function = new Twig_SimpleFunction("fh_{$method}", array($object, $method), array('is_safe' => array('html')));
    $twig->addFunction($function);
}
请注意,不能在函数名中使用点(
),因此需要调用:

{{ fh_test() }}
{{ fh_test() }}