Using Twig 3.0, I was wondering if it is possible to create Twig extensions that intervene when the dot operator is being processed?
So, suppose I have this expression
{{ myRecord.myField }}
and it won't work even though myRecord is a known thing, because it doesn't have a field called myField.
But I would want Twig to run my own custom extension code to figure out what to use for .myField, is that possible? How?
I know this can be achieved with different notations using a function or filter (e.g. myRecord|getCustomField(myField)), but I want to keep the dot notation because I feel it's particularly adequate for my purposes.
The
CoreExtensionsupportsget*,is*,has*method lookups for the dot.https://github.com/twigphp/Twig/blob/3.x/src/Extension/CoreExtension.php#L1563
So if your class has a
myRecord::getMyFieldmethod you can access it viamyRecord.myFieldin Twig.Another option is to use the
__callmagic method: https://www.php.net/manual/en/language.oop5.overloading.php#object.callThe more complex and flexible approach that doesn't require altering the
myRecordclass would involve writing a custom Extension to replace nodes. Here's a simple example that you can modify to create MethodCall nodes on the class, for example.Hope this helps.