2011-04-14 46 views
0

我已經生成一個查詢,如下,並將結果格式化爲鏈接:在Drupal 7中呈現查詢結果的正確方法是什麼?

$result = db_query("SELECT name FROM {taxonomy_term_data} WHERE vid = :val", array(':val' => '1')); 
    $list = array(); 
    foreach ($result as $record) { 
    $list[] = l($record->name, 'blog/' . $record->name); 
    } 

現在,我想使這個數組作爲一個無序列表,並返回一個塊。什麼是適當的函數/語法來做到這一點?

另外,哪裏是與渲染有關的函數的一個很好的參考?

在此先感謝您的幫助!

回答

0

請注意,「呈現查詢結果的正確方法」不存在,但有很多方法。他們可以作爲一個列表,作爲一個表格和許多其他方式呈現。你所要求的是呈現鏈接列表的正確方式,即這些鏈接來自數據庫是不相關的。

請參閱http://api.drupal.org/api/drupal/includes--theme.inc/function/theme_links/7。而不是直接調用theme(),也可以使用所謂的可渲染數組,這是Drupal 7中的一項新功能,也是現在的首選方法。

$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); 
0

下面介紹一種方法。建立$vars數組並把它傳遞給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

+0

您呼叫的主題功能失常,這應該是主題( 'item_list',$瓦爾)。否則,這也適用,是的,但如果列表僅包含鏈接,則沒有必要直接使用theme_links()。 – Berdir 2011-04-17 18:18:05

+0

@Berdir:嗯.. theme_item_list()是Drupal api [鏈接](http://api.drupal.org/api/drupal/includes--theme.inc/function/theme_item_list)的一部分,但使用theme_links()有點更優雅。' $ vars ['links'] = $ list; $ vars ['heading'] ='按類別排序條目'; $ vars ['attributes'] = array( 'id'=>'blog-taxonomy-block', ); $ content = theme_links($ vars); return $ content; ' – starsinmypockets 2011-04-17 20:39:42

+0

是的,但是,您不能直接調用主題函數,而是使用theme()。這打破了主題系統的全部目的(這些功能可以被主題覆蓋)。 – Berdir 2011-04-18 07:22:51

相關問題