DrupalX

Extension
Framework

Singleton operator

The singleton method is a wrapper method around the factory method that is normally used the most when instantiating new objects. It must be callable without any arguments and then usually returns the same read-only object everytime it is called. It almost works like Drupal's services - with the difference that you don't have to memorize a complicated service name but the class name you probably already know from other contexts. For example, to print the current Node's title from within a field template you can just call:

{{Node::current().$title}}

In Twig, any methods or properties of classes that provide such a singleton method are even easier to access than in PHP, because you can use DrupalX's singleton operator ("->"). The previous example can thus be written even shorter as:

{{Node->$title}}

Another example is how you can determine if the user is logged in from within a Twig template and then print a personal welcome message if that's the case:

{% if not User->anonymous %}
Welcome, {{ User->name }}
{% endif %}