Search code examples
drupal-7drupal-theming

Drupal 7 How to use render element instead of variables in hook_theme()


I'm having trouble understanding the 'render element' key purpose when implementing hook_theme().

function personal_news_theme($existing, $type, $theme, $path) {
  return array(
    'teaser_list_by_user' => array(
      'render element' => 'element',
    ),
  );
}

I did my research and the way I understand it, the render element key is use when creating a theme function to modify another theme function's output ONLY! And there's no way to use it as to implement a new theme function. If I'm wrong, how can I use it instead of variables?


Solution

  • In the example below, I created a new theme function using a render element.

    /**
     * Implements hook_theme().
     */
    function rojo_theme() {
      $items = array(
        'rojo_content' => array(
          'render element' => 'element',
        ),
      );
      return $items;
    }
    
    /**
     * Theme function.
     */
    function theme_rojo_content($vars) {
      return '<pre>' . print_r($vars, TRUE) . '</pre>';
    }
    
    /**
     * Render function.
     */
    function rojo_render() {
      $build = array(
        '#theme' => 'rojo_content',
        '#module' => 'rojo',
        'content' => 'Page content for the render function',
        'list' => array('one', 'two'),
        'tag' => 'div',
      );
      return render($build);
    }
    

    This will print the output of the $vars passed into the theme function. From here, you should be able to see what is going on. The #theme property will be called with theme() and passed the $build array during the render() process. Notice I added #module property and Drupal added the #printed / #children properties.

    This is purely an example to demonstrate the creation of a new theme function using render element and argument passing. I hope this helps somebody out.

    Array
    (
      [element] => Array
        (
          [#theme] => rojo_content
          [#module] => rojo
          [content] => Page content for the render function
          [list] => Array
            (
              [0] => one
              [1] => two
            )
          [tag] => div
          [#printed] => 
          [#children] => 
        )
    )