Thursday, August 29, 2013

Drupal 8 and Twig

Research

I want to create a Drupal 8 module which is up to the goals that are set for the version, especially the templates.  Drupal 8 includes Twig as template engine.

When you look for Drupal 8/Twig tutorials you get the explanation why it's good to have a template engine and how to use it. Which is great, but when you use symfony the views go in a Recources/views directory, and that is something the tutorials fail to mention most of the time.

When you see Twig files they are stored in a templates directory. The strange thing is that the templates directory is located in the root of the module. If you want a controller to use a template it feels wrong because that is stored in the lib/Drupal/module_name/Controller directory.

Solution

After a bit of code searching I found the twig loader instance is attached to the container as twig.loader. Which resulted in following controller code.

For people who are not familiar with controllers I will go line by line.

On line 3 you set the namespace of your controller. This prevents problems with other controllers in Drupal.

Lines 5 to 7 tell which objects are going to be used.

On line 9 you create the class.

The __construct method is called when the controller is created as an object.
Line 12 is the line I was searching for. This adds the View directory on the same level as the Controller directory to the loader, and this is how twig will find your templates.
On line 14 twig is attached to controller.

The create method is called by Drupal, and it makes an object of the class. 

The displayTwig method shows how to render a Twig file from the View directory.

Caveats

It seems best to prefix the Twig files of your module with the module name to prevent similar named views to be loaded.

If you have multiple controllers it is best to create a class your actual controllers can inherit form so you don't have to repeat the Twig binding code.