【问题标题】:Drupal 7 How to use render element instead of variables in hook_theme()Drupal 7 如何在 hook_theme() 中使用渲染元素而不是变量
【发布时间】:2014-05-14 01:40:49
【问题描述】:

在实现 hook_theme() 时,我无法理解“渲染元素”的关键目的。

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

我做了我的研究和我理解的方式,render element 键仅用于创建主题函数来修改另一个主题函数的输出!而且没有办法用它来实现一个新的主题功能。 如果我错了,我该如何使用它而不是variables?

【问题讨论】:

    标签: drupal-7 drupal-theming


    【解决方案1】:

    在下面的示例中,我使用渲染元素创建了一个新的主题函数。

    /**
     * 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);
    }
    

    这将打印传递给主题函数的$vars 的输出。从这里,您应该能够看到发生了什么。 #theme 属性将使用theme() 调用,并在render() 过程中传递$build 数组。注意我添加了#module 属性,Drupal 添加了#printed / #children 属性。

    这纯粹是一个演示使用render element 和参数传递创建新主题函数的示例。我希望这可以帮助某人。

    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] => 
        )
    )
    

    【讨论】:

      【解决方案2】:

      如果您的主题函数返回一个数组 - 您可以指定数组的哪个键用于渲染。

      渲染元素:要传递给主题函数的可渲染元素或元素树的名称。此名称用作在预处理和处理函数中保存可渲染元素或树的变量的名称。

      (来源:hook_theme)

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-07-21
        • 1970-01-01
        相关资源
        最近更新 更多