How to hook_theme in drupal 8 as I did in drupal 7

No replies
Last seen: 3 years 39 weeks ago
Joined: 2013-03-17

In drupal 7, i used hook_theme to render form elements in a table. I set #theme key in my form on a fieldset that is a parent container to many form fields. My hook theme looked like this:

 * Implements hook_theme().
function food_theme() {
  $themes = array(
    'nutrients_form' => array(
      'render element' => 'form',
      'file' => '',
      'path' => drupal_get_path('module', 'food') . '/themes',
  return $themes;

And the file looks like this:
 * Theme function for nutrients form.
function theme_nutrients_form($vars) {
  $form = $vars['form'];
  $header = array();
  $rows = array();
  foreach (element_children($form) as $key) {
    $class = isset($form[$key]['#attributes']['indent']) ? 'indent' : 'no-indent';
    $required = !empty($form[$key]['#required']) ? ' <span class="form-required" title="This field is required.">*</span>' : '';
    $label = $form[$key]['#title'] . $required;
    $row = array();
    $row['data'][] = array('data' => $label, 'class' => $class);
    $row['data'][] = drupal_render($form[$key]);
    $rows[] = $row;
  return theme('table', array(
    'header' => $header,
    'rows' => $rows,
    'attributes' => array('id' => 'nutrients-table'),

I get errors related to missing twig file when attempting to use the same code in Drupal 8 and I'm a bit lost how to accomplish the same thing.

Add to playlist

Add to , or

Add to new playlist:

Add to playlist
This is a member-only feature
But, it's easy to become a member

Add to cart:

Contact us

Below are the supported keyboard shortcuts for our video player.

Start / stop video
Go to next video
Go to previous video
Increase or decrease player speed by 20%
Skip ahead or go back by 15 seconds
Jump to a percentage (2 is 20%, for example)
Toggle full screen
Videos Pricing More Search
BuildAModule Logo Icon BuildAModule Logo Icon
Become a member!
1 month
6 months
10% off
12 months
20% off
All memberships come with the following:
24 / 7 access to the entire 1800+ video library
An innovative video player with a rolling transcript
Extensive Drupal and cross-platform training
A thorough and thoughtful training style
Progress tracking
Take notes on specific video sections
Intuitive multi-user management
How many users?
Go solo with a single user, or give multiple team members access through one account and get discounts by bundling multiple users into a single membership.