Drupal 8 Module Port - Theming and Twig

This is Part 5 of a blog series about my recent experiences of porting the Instagram Block module from Drupal 7 to Drupal 8. Since Drupal 8 is still in alpha, APIs are subject to change. Also I may not be using best practises so commenting is heavily appreciated!

Theming content in Drupal 8 is very different to Drupal 7. For more in depth information about which problems were solved and why, have a look at this great presentation (http://www.youtube.com/watch?v=adrW67KrdUY) by Jen Lampton at an East Bay Drupal Users group meetup.

In Drupal 8 Twig is a great format to work with, amoung other reasons, because it is readable, intuitive and automatically sanitised.

Hurray for closing security holes!

Show me code!

I will be looking at how to much from a theme function in Drupal 7 to a twig file in Drupal 8.

In Drupal 7, you could have a render array with a #theme key, a theme hook to map a theme key to a theme function, and said theme function. On top of this, you could have preprocess functions, template files, pre-render, post-render, and a huge mess of code.

Drupal 8 doesn't change EVERYTHING. We still have render arrays and hook_theme, and even preprocess functions to modify and clean up our variables. But the big difference is that we pass those variables to a *.html.twig template file

Important Notes

You can immediately notice how much easier it is to see what is going on. To use any of your theme variables, just pop them in {{}}'s and twig will work out whether to print/render/print render it. As I stated above, twig takes care of sanitizing code and knows if the code came from the database or user input. The {% spaceless %} tag even strips out whitespace for you, and you/the themer can focus on what is important. Beautiful themes!