What is the proper way to render a query result in Drupal 7?
I've generated a query, as follows, and formatted the results as links:
$result = db_query("SELECT开发者_如何学Go name FROM {taxonomy_term_data} WHERE vid = :val", array(':val' => '1'));
$list = array();
foreach ($result as $record) {
$list[] = l($record->name, 'blog/' . $record->name);
}
Now I would like to render this array as an unordered list and return it to a block. What's the proper function/syntax for doing this?
Also, where is a good reference for functions related to rendering?
Thanks in advance for any help!
Note that "the proper way to render a query result" does not exist, there are many ways. They could be rendered as a list, as a table and many other ways. What you are asking for is the proper way to render a list of links, that these links are coming from the database is not relevant.
See http://api.drupal.org/api/drupal/includes--theme.inc/function/theme_links/7. And instead of calling theme() directly, you can also use the so called renderable arrays which are a new feature in Drupal 7 and the preferred way to do this now.
$result = db_query("SELECT name FROM {taxonomy_term_data} WHERE vid = :val", array(':val' => '1'));
// Prepare renderable array, define which theme function shall be used.
// The other properties match the arguments of that theme function.
$list = array(
'#theme' => 'links',
'#links' => array(),
);
foreach ($result as $record) {
// Add each link to the array.
$list['#links'][] = array('title' => $record->name, 'href' => 'blog/' . $record->name));
}
// Now you can call drupal_render() and return or print that result.
// If this is inside a block or page callback, you can also directly return
// $list and Drupal will call drupal_render() automatically when the rest of
// the page is rendered.
return drupal_render($list);
Here's one way to do it. Build $vars
array and pass it to theme_item_list($vars)
:
$vars['items'] = $list;
$vars['title'] = 'Sort entries by category';
$vars['type'] = 'ul';
$vars['attributes'] = array(
'id' => 'blog-taxonomy-block',
);
$content = theme_item_list($vars);
return $content;
http://api.drupal.org/api/drupal/includes--theme.inc/function/theme_item_list/7
精彩评论