Drupal 9 多語言站點解決 Paragraphs 字段在custom block 中I18翻譯無法正確顯示問題

Drupal 9 多語言站點解決 Paragraphs 字段在custom block 中I18翻譯無法正確顯示問題
Fix paragraphs field translate failed in Drupal 9 custom block

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);
        }
      }
    }
  }
}
web/modules/custom/custom_module/custom_module.module

延伸閱讀:

Y Cheung

Y Cheung

Blogger, Programer & Traveler.
Shanghai