简体   繁体   中英

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. Basically a simple function that could parse out the PHP and run the code in the template.

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.

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. You can create filters or functions and pass strings as arg.

How? This way (orginal answer):


Anywhere inside the controller you're loading 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. You should just investigate where to add the Twig simple function/filter.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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