Support for Drupal 7 is ending on 5 January 2025—it’s time to migrate to Drupal 10! Learn about the many benefits of Drupal 10 and find migration tools in our resource center.
Is there a way to use a Twig variable in a PHP filter in Twig Tweak?
I want to be able to process using PHP in my template, but I need to pull in a variable from the view.
For example {{ 'print title;' | php }} where title is equivalent to the Twig {{ title }} or as in {{ '$title = title; print title;' | php }}
Comments
Comment #2
Chi CreditAttribution: Chi commentedThat is not supported yet. Though it's not a big deal to pass Twig context into PHP filter.
Comment #3
mxwright CreditAttribution: mxwright as a volunteer commentedCan you explain how to pass a Twig context into PHP? I don't necessarily need to use a Twig variable in the php code, but I need to be able to use a field (from Views) in it. I assume there's a way to do it, but I can't figure it out. Like {{ 'print $node->field_email->value;' | php }} or {{ 'print $twig->render(field_email);' | php }} - those are just guesses but I'm clearly missing something.
Comment #4
Chi CreditAttribution: Chi commentedThat requires changes in Twig Tweak PHP filter.
Also as you craft your code yourself you can do some crazy thins with PHP code string. Like follows.
{{ 'var_dump(' ~ node ~ ');' |php }}
. Though I would not recommend it. It's much easier to achieve in preprocess hook.Comment #7
Chi CreditAttribution: Chi commentedFixed in Twig Tweak 2.6. Thanks for the report.