DrupalX

Extension
Framework

Static call operator

DrupalX introduces a new operator "::" to call static methods of "Twig-compatible" classes from Twig. It works almost like you are used to from PHP. While you still cannot instantiate arbitary classes (there is no "new" operator in Twig with or without DrupalX) - you can use the static factory methods of those classes to instantiate new objects. With "Twig-compatible" we mean that those classes have to implement a special interface to declare they are suitable for use inside Twig.

The still missing "new" operator as well as the restriction of the static call operator to only work for Twig-compatible classes are intentional: As explained in the introduction we don't want to turn Twig into a full-fledged programming language. Consequently we prevent you from accessing any arbitrary class. Please use PHP if you want to do complicated things - especially those that involve modify data or writing to disk etc. 

All classes inside Twig are read-only. Remember again, we don't want to allow any data modification to keep the strict separation between data modifcation and output. Thus, for a class to be Twig-compatible, it has to implement a method "readonly" that is automatically called whenever a factory method returns such a class to Twig code. This method will irrevocably mark this object by setting the "readonly" property to true. It can never be set to false again for this object. A class must respect this property and deny any modifying changes. For example, in read-only-mode, you can load a node by calling Node::load(id) but you cannot delete or save the resulting object. Attempting to do so will result in an exception.

{% set nodes=Node::queryAll({type:"news"}) %}
There are currently {{ nodes | length }} news items available.