欢迎各位兄弟 发布技术文章

这里的技术是共享的

You are here

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?

shareimprove this question
 

正确答案 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 $buildarray 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 elementand 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] => 
    )
)
shareimprove this answer
 

If your theme function returns an array - you can specify which key of the array to use for rendering.

render element: The name of the renderable element or element tree to pass to the theme function. This name is used as the name of the variable that holds the renderable element or tree in preprocess and process functions.

(Source: hook_theme)


普通分类: