drupal自定义块模块:如何从hook_block_view(...)显示动态生成的html?

时间:2012-09-26 21:15:14

标签: html drupal dynamic view generated

我想输出动态生成的html内容而不是可翻译的消息,但我无法使其工作:

function custom_logo_module_block_view($delta = '') {

    // don't worry about switch($delta) logic

    // perform some operations and then display some generated html

    // (maybe use the template(...) function)

    // works fine but i'd like to print html
    $block['content'] = t('No content available.');

    return $block;
}

如何将生成的html打印成块?

我找不到任何解决方案或代码示例。我想我可能指向错误的方向,所以欢迎最佳实践建议。

1 个答案:

答案 0 :(得分:0)

function custom_logo_module_block_view($delta = '') {
  $block = array();
  if ($delta == 'example') {
    $block = array(
      'subject' => t('Active users list'),
      'content' => example_block_content()
    );
  }
  return $block;
}

function example_block_content() {
  // Query for active users from database
  $users = db_select('users', 'u')
    ->fields('u', array('uid', 'name'))
    ->condition('u.status', 1)
    ->execute()
    ->fetchAll();

  // Prepare items for item list
  $items = array();
  foreach ($users as $user) {
    $items[] = l($user->name, "user/{$user->uid}");
  }

  $output = t('No active users available.');

  if (!empty($items)) {
    $output = theme('item_list', array('items' => $items));
  }

  return $output;
}

有关您的评论的更新...

据我所知,some result表示从数据库生成数据。在这种情况下,您可以尝试这样的事情:

function example_block_content() {
  // Query for active users from database
  $users = db_select('users', 'u')
    ->fields('u', array('uid', 'name'))
    ->condition('u.status', 1)
    ->execute()
    ->fetchAll();

  $output = '';
  foreach ($users as $user) {
    $output.= '<div>'. $user->name .'</div>';
  }

  $output = "<div>Hello World". $output ."</div>";

  return $output;
}

这将为您提供以下输出:

<div>Hello World
  <div>admin</div>
  <div>ndrizza</div>
  <div>Vlad Stratulat</div>
  ...
</div>

或者您可以尝试:

function custom_logo_module_block_view($delta = '') {
  $block = array();
  if ($delta == 'example') {
    $block = array(
      'subject' => t('Active users list'),
      // this will return "Hello World + some result" text inside <div>
      'content' => "<div>Hello World + some result</div>"
    );
  }
  return $block; 
}

这两种方式都有效,但它们不是正确的方法。生成内容的正确方法是我的第一个答案。阅读Drupal中有关主题的更多信息。