在 Drupal Views 的 Row style 模板中,需根據節點 ID ($row->nid) 關聯查詢術語(國家、投資類型),並結合 Views 提供的 $fields 變量輸出自定義 HTML。
<?php
// 1. 獲取節點 ID
$nid = $row->nid;
// 2. 查詢詞彙表 1 (vid=1) 關聯的術語名稱(國家)
$country = db_result(db_query(
"SELECT name FROM {term_data} td
JOIN {term_node} tn ON tn.tid = td.tid
WHERE td.vid = %d AND tn.nid = %d", 1, $nid
));
// 3. 查詢詞彙表 2 (vid=2) 關聯的術語名稱(投資類型)
$investment = db_result(db_query(
"SELECT name FROM {term_data} td
JOIN {term_node} tn ON tn.tid = td.tid
WHERE td.vid = %d AND tn.nid = %d", 2, $nid
));
?>
<div class="article-l">
<?php echo $fields['title']->content ?>
<div class="left-content">
<?php echo $fields['body']->content ?>
</div>
</div>
<div class="article-r">
<div class="right-content">
<?php echo $fields['body_1']->content ?>
</div>
<div class="article-link">
<?php echo instanter_country_code($country) ?>
<?php echo $fields['created']->content ?>
<?php echo instanter_investment_code($investment) ?>
<?php echo $fields['view_node']->content ?>
</div>
</div>
<div class="clear-both"></div>
db_query() 使用佔位符 %d 防注入,Drupal 7 核心資料庫 API。db_result() 直接取單值(適用於單行單列結果)。{term_data}、{term_node} 為 Drupal 表前缀自動替換語法。$fields['field_name']->content 為 Views 預處理後的字段渲染輸出(已含格式化)。instanter_country_code()、instanter_investment_code() 用於術語代碼轉換/圖標輸出。hook_views_pre_render() 或字段處理器中預先加載關聯數據,減少 N+1 查詢。EntityFieldQuery 或 db_select() 替代原生 SQL(Drupal 7/8/9/10)。<?php
// 在預處理函數中
function MYTHEME_preprocess_views_view_row(&$variables) {
$row = $variables['row'];
$node = $row->_entity; // 節點實體
$variables['country'] = $node->get('field_country')->entity->label();
$variables['investment'] = $node->get('field_investment')->entity->label();
}
// 模板 twig
<div class="article-l">
{{ fields.title.content }}
<div class="left-content">{{ fields.body.content }}</div>
</div>
<div class="article-r">
<div class="right-content">{{ fields.body_1.content }}</div>
<div class="article-link">
{{ country }} {{ fields.created.content }} {{ investment }} {{ fields.view_node.content }}
</div>
</div>