AEM提供 翻译集成框架 对于Headless内容,允许轻松翻译内容片段和支持资产,以便跨区域设置使用。 该框架用于翻译其他AEM内容,例如页面、体验片段、资源和Forms。 一次 headless内容已翻译和发布后,即可供Headless应用程序使用。
确保AEM中的本地化内容片段遵循 推荐的本地化结构.
区域设置文件夹必须是同级文件夹,并且文件夹名称而不是标题必须是有效的 ISO 639-1代码 表示文件夹中所包含内容的区域设置。
区域设置代码也是用于筛选GraphQL查询返回的内容片段的值。
区域设置代码 | AEM路径 | 内容区域设置 |
---|---|---|
de | /content/dam/…/de/… | 德语内容 |
en | /content/dam/…/en/… | 英语内容 |
es | /content/dam/…/es/… | 西班牙语内容 |
AEM提供 _locale
GraphQL筛选器,可按区域设置代码自动筛选内容。 例如,查询 WKND站点项目 可以使用新的持久查询完成 wknd-shared/adventures-by-locale
定义为:
query($locale: String!) {
adventureList(_locale: $locale) {
items {
_path
title
}
}
}
此 $locale
中使用的变量 _locale
筛选器需要区域设置代码(例如 en
, en_us
,或 de
),如中所指定 基于AEM资产文件夹的本地化惯例.
让我们创建一个简单的React应用程序,该应用程序通过使用区域设置选择器,控制要从AEM查询的Adventure内容 _locale
筛选条件。
时间 英语 在区域设置选择器中选中,然后在 /content/dam/wknd/en
在以下情况下返回 西班牙语 选择,然后选择下的西班牙语内容片段 /content/dam/wknd/es
,等等。
LocaleContext
首先,创建 React上下文 允许在React应用程序的组件中使用区域设置。
// src/LocaleContext.js
import React from 'react'
const DEFAULT_LOCALE = 'en';
const LocaleContext = React.createContext({
locale: DEFAULT_LOCALE,
setLocale: () => {}
});
export default LocaleContext;
LocaleSwitcher
React组件接下来,创建一个区域设置切换器React组件,该组件将 LocaleContext 用户的选择的值。
此区域设置值用于驱动GraphQL查询,确保它们仅返回与所选区域设置相匹配的内容。
// src/LocaleSwitcher.js
import { useContext } from "react";
import LocaleContext from "./LocaleContext";
export default function LocaleSwitcher() {
const { locale, setLocale } = useContext(LocaleContext);
return (
<select value={locale}
onChange={e => setLocale(e.target.value)}>
<option value="de">Deutsch</option>
<option value="en">English</option>
<option value="es">Español</option>
</select>
);
}
_locale
过滤器Adventures组件按区域设置查询AEM的所有冒险并列出其标题。 这是通过使用将存储在React上下文中的区域设置值传递到查询来实现的 _locale
筛选条件。
此方法可以扩展到应用程序中的其他查询,确保所有查询仅包含由用户的区域设置选择指定的内容。
在自定义React挂接中执行针对AEM的查询 getAdventuresByLocale,有关“查询AEM GraphQL”文档的更多详细信息,请参阅.
// src/Adventures.js
import { useContext } from "react"
import { useAdventuresByLocale } from './api/persistedQueries'
import LocaleContext from './LocaleContext'
export default function Adventures() {
const { locale } = useContext(LocaleContext);
// Get data from AEM using GraphQL persisted query as defined above
// The details of defining a React useEffect hook are explored in How to > AEM Headless SDK
let { data, error } = useAdventuresByLocale(locale);
return (
<ul>
{data?.adventureList?.items?.map((adventure, index) => {
return <li key={index}>{adventure.title}</li>
})}
</ul>
)
}
App.js
最后,通过将React应用程序与封装在一起, LanguageContext.Provider
并设置区域设置值。 这允许其他React组件, 区域设置切换器、和 冒险 以共享区域设置选择状态。
// src/App.js
import { useState, useContext } from "react";
import LocaleContext from "./LocaleContext";
import LocaleSwitcher from "./LocaleSwitcher";
import Adventures from "./Adventures";
export default function App() {
const [locale, setLocale] = useState(useContext(LocaleContext).locale);
return (
<LocaleContext.Provider value={{locale, setLocale}}>
<LocaleSwitcher />
<Adventures />
</LocaleContext.Provider>
);
}