back

Knowlegde

Knowledge Centre

Drupal lesson: Drupal hook_theme()

by editor | 15.04.2016

Drupal lesson: Drupal hook_theme()

 

FIRST OF ALL, LET’S SAY WHAT THE HOOK_THEME() IS

Basically, it’s a place where a module can define its themes, which can then be overridden by any other module/theme. This will enable any module to use hooks to change variables that have passed to the eventual theme function or template file.

 

HOW TO INITIALIZE A THEME FUNCTION:

This is the most simple way: theme('poll_results', array('raw_title' => 'title', 'results' => $results, etc...));

In Drupal 8, theme() is a private function, _theme()
Drupal is providing 'named arguments' through either a keyed array passed to the theme function, or as hashed keys in a render array.
The 'render element' tells the theme system that the theme function will be called using a render array, with one named argument (in this case form).

fish-hook
Top
default
$build = array(
  '#theme' => 'poll_choices',
  '#form' => $form
);
For the template key you could use:
'poll_vote' => array(
  'template' => 'poll-vote',
  'render element' => 'form',
)

 

To return the output for a theme function, implement the physical function name or use a template file. If the template key is empty Drupal will assume you've implemented a physical function and will try to call it.

Template files are preferable if you have a fair bit of HTML to output for a theme, or you simply don't like writing HTML in strings inside PHP. Either-way, the variables passed when you call the theme (either using theme() or a render array as described above) are themselves passed through to the template file or theme function. 

function theme_poll_results(&$vars) {
  $raw_title = $vars['raw_title'];
  $results = $vars['results'];
  // etc...
}

 

When using a template file instead for the same method the variables would be available as $raw_title, $results, etc, as Drupal runs extract on the $vars before parsing the template file.

Hope this helped, at least a tiny little bit.

  • Knowlegde
    Knowledge Centre
    Replace a field's content based on another field using AJAX
    editor
  • Knowlegde
    Knowledge Centre
    Port your sites to Drupal 9
    editor
  • Knowlegde
    Knowledge Centre
    Drupal 8 or Drupal 9
    editor

Post a Comment.