Drupal 9 多語言站點啟用 Paragraphs 模組,如果在 custom block 中使用了 paragraphs 類型的字段 ,會遇到字段內文字的翻譯無法顯示問題。該 paragraphs 字段的內容始終加載的是 default 的語言內容(通常是英文),需要在custom module 代碼中使用 hook_preprocess_block()
修改一下。
環境設定:
- Drupal v9.3.3
- Paragraphs v1.12.0
代碼如下:
1// web/modules/custom/custom_module/custom_module.module
2
3/**
4 * Implements hook_preprocess_HOOK().
5 */
6function custom_module_preprocess_block(&$variables) {
7 if ($variables['base_plugin_id'] == 'block_content' && isset($variables['content']['field_paragraphs'])) {
8 $lang = \Drupal::languageManager()->getCurrentLanguage()->getId();
9 if (count($variables['content']['field_paragraphs']['#items'])) {
10 foreach ($variables['content']['field_paragraphs']['#items'] as $item) {
11 if ($item->entity->hasTranslation($lang)) {
12 $item->entity = $item->entity->getTranslation($lang);
13 }
14 }
15 }
16 }
17}