简体   繁体   English

PHP-在TWIG模板中传递PHP函数

[英]PHP - Passing PHP functions within TWIG templates

I'm trying to figure out a way that I can pass PHP code directly within the templates in TWIG without having to create separate extensions for each function. 我试图找出一种方法,可以在TWIG的模板中直接传递PHP代码,而不必为每个函数创建单独的扩展。 Basically a simple function that could parse out the PHP and run the code in the template. 基本上是一个简单的函数,可以解析PHP并运行模板中的代码。

Example: 例:

$function = new Twig_SimpleFunction('php_parse_function', function () {
     //parse php code here
});
$twig->addFunction($function);

Use-case Example: 用例示例:

{{ php_parse_function | php code }}

The problem with doing something like this is that I would have to include an entire code-block in a string, which is to print html encapsulated in another string, which will have class/other-attributes in another layer of quotes. 这样做的问题是,我必须在字符串中包含整个代码块,这是要打印封装在另一个字符串中的html,这将在另一层引号中包含类/其他属性。

Example: 例:

{{php_parse_function | "echo '<section class=\'Yo\' id=\'2\'>'</section>" }}

So is there a workaround for something like this? 那么是否有解决此类问题的方法?

EDIT (after question edit) 编辑 (问题编辑后)

No, It's not possible to execute php code directly from Twig. 不,不可能直接从Twig执行php代码。 You can create filters or functions and pass strings as arg. 您可以创建过滤器或函数,并将字符串作为arg传递。

How? 怎么样? This way (orginal answer): 这样(原始答案):


Anywhere inside the controller you're loading Twig: 在控制器内部要加载Twig的任何位置:

// ...
$twig = new Twig_Environment($loader, $params); // load Twig env
$tsf = new Twig_SimpleFunction('fooTwig', function ($str) {
    return eval($str);
});
$twig->addFunction($tsf);
// ...

Then: 然后:

{{ fooTwig('echo "Hello, World! What kind of sorcery is this? F in hex is "; echo hexdec("F");') }}

And remember you can use filters too! 请记住,您也可以使用过滤器!

Controller: 控制器:

// ...
$twig = new Twig_Environment($loader, $params); // load Twig env
$tsf = new Twig_SimpleFilter('fooTwig', function ($str, $fn) {
    $args = array_merge(array($str), array_slice(func_get_args(), 2));
    return call_user_func_array($fn, $args);
});
$twig->addFilter($tsf);
// ...

Then: 然后:

{{ 'F'|fooTwig('hexdec') }}

If you are using Symfony2 or any other framework, is the same logic. 如果您使用的是Symfony2或任何其他框架,则逻辑相同。 You should just investigate where to add the Twig simple function/filter. 您应该研究添加Twig简单功能/过滤器的位置。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM