Drupal 9 多語言站點啟用 Paragraphs 模組,如果在 custom block 中使用了 paragraphs 類型的字段 ,會遇到字段內文字的翻譯無法顯示問題。該 paragraphs 字段的內容始終加載的是 default 的語言內容(通常是英文),需要在custom module 代碼中使用 hook_preprocess_block()
修改一下。
環境設定:
- Drupal v9.3.3
- Paragraphs v1.12.0
代碼如下:
/**
* Implements hook_preprocess_HOOK().
*/
function custom_module_preprocess_block(&$variables) {
if ($variables['base_plugin_id'] == 'block_content' && isset($variables['content']['field_paragraphs'])) {
$lang = \Drupal::languageManager()->getCurrentLanguage()->getId();
if (count($variables['content']['field_paragraphs']['#items'])) {
foreach ($variables['content']['field_paragraphs']['#items'] as $item) {
if ($item->entity->hasTranslation($lang)) {
$item->entity = $item->entity->getTranslation($lang);
}
}
}
}
}
延伸閱讀:
- Simon Ramsay: Creating Customs Blocks and Custom Block Types in Drupal 9.
- Drupal official documents: Multilingual Paragraphs configuration .