内容翻译

admin 提交于 周三, 06/07/2023 - 15:21

内容翻译

内容翻译指的是对 Content entity 的字段数据进行翻译。

首先要在 admin/config/regional/content-language 对要进行翻译的 Content type 启用翻译并选择要翻译的字段。 要注意并不是所有字段都能启用翻译,这由 Content type 的定义所决定。

对字段启用翻译,本质上是在系统中创建了几个重要的配置。

  • language.content_settings.*.*.yml
  • core.base_field_override.*.*.*.yml 默认会对所有可启用翻译的字段启用翻译,如果自定义了,会通过这个配置文件来覆盖字段的默认设置。 要注意的是同,这个配置不单单只是用来覆盖字段的可翻译性的。

开启后,在创建新数据时,便可以指定数据的语言版本,并且可以对已有的数据进行翻译。

如果是通过代码创建数据,可以通过 addTranslation 添加翻译版本。

$term = Term::create([
    'name' => 'Apple',
    'vid' => 1,
  ]);
// Add translation.
$term->addTranslation('zh-hans', ['name' => '苹果',]);
$term->save();

$node = Node::load(1);
if (!$node->hasTranslation('zh-hans')) {
    // 从源语言创建翻译
    $translation = $node->addTranslation('zh-hans', $node->toArray());
    $node->save();
    // 修改某个字段的翻译
    $translation->set('title', '修改标题');
    $node->save();
}

如果是通过 migrate 迁移数据,通过指定 langcode 字段,并在 destination 中指定 translations: true来导入翻译内容。

blog_posts.yml