BADCamp logo

BADCamp 2015: Transitioning From theme() and Theme Functions to Render Arrays and Templates

I was fortunate to attend and speak at BADCamp for the first time this year. BADCamp is the Bay Area Drupal Camp, held annually in Berkeley, CA. I don't know the official numbers, but I believe over 1,000 were in attendance, giving it the feel of a smaller DrupalCon. The camp was well organized, the sessions were high quality, and I met and got to know quite a few great people.

Anyone who wasn't able to attend can watch my session, 7 to 8: Transitioning From theme() and Theme Functions to Render Arrays and Templates, here:

My slides are also available online. The video and slides include in-depth examples, but for the TL;DW crowd more interested in the key takeaways:

Render Arrays > theme()

The theme() function no longer exists in Drupal 8. Instead, render markup by passing render arrays to the template. Start using render arrays instead of theme() in Drupal 7 right now. Not only will it make the code easier to port to Drupal 8, but there are other advantages.

Using render arrays allows for the data to remain an array until the template renders it into markup. Waiting to render markup allows other modules or themes to intercept and alter the data before it is rendered. This is typically done with preprocess hooks.

Templates > Theme Functions

When Drupal 7 goes to render markup, it does so with either a theme function, such as theme_image(), or a template. Theme functions contain a lot of logic and are a tough way to write and alter markup. Overriding theme functions also involves copying a significant amount of code to make changes.

Instead of writing theme functions, write templates. Keep the logic in preprocess and process functions. This separation will make altering the logic and markup much easier. Other modules or themes can easily use preprocess hooks or override templates as needed.

Drupal 8 has taken this approach. While theme functions can still exist in Drupal 8, all core theme functions were converted to templates.

More information

For more on this topic, check out these resources on drupal.org:

There were also a number of other sessions at BADCamp related to this topic. They included:

Thanks again to the BADCamp organizers. I hope to see everyone again next year!

Drupal Drupal 8 Drupal 7 Front-End Development Presentations
Gus Childs Headshot

Gus is a mobile first front-end developer that prioritizes user experience. He isn't afraid to write a module and is a community contributor and speaker.