You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

AEM 6.2+ 程序化切换语言及页面即时渲染实现咨询

如何在AEM中设置语言后立即刷新页面渲染新语言?

当然可以实现!结合AEM的Granite I18n机制和前端逻辑,完全能做到切换语言后页面立刻用新语言渲染。下面是具体的实现思路和可行方案:

核心思路

Granite.I18n.setLocale('<locale>')只是修改了前端的i18n上下文,但页面上已渲染的文本不会自动更新。我们需要在切换locale后,主动更新页面内容或者触发页面重新渲染。

方案一:前端动态更新翻译文本

如果你的页面内容大多是通过前端data-i18n标记的翻译项,可以写一个工具函数遍历并更新这些元素:

  1. 首先处理语言切换的触发事件(比如下拉选择、按钮点击):
// 假设用户选择了法语,locale为'fr-FR'
document.getElementById('language-select').addEventListener('change', function(e) {
  const newLocale = e.target.value;
  // 1. 设置新的locale
  Granite.I18n.setLocale(newLocale);
  // 2. 刷新所有翻译文本
  refreshTranslatedContent();
  // 3. 可选:持久化用户选择
  localStorage.setItem('preferredLocale', newLocale);
});
  1. 实现刷新翻译内容的函数:
function refreshTranslatedContent() {
  // 遍历所有带data-i18n属性的元素
  document.querySelectorAll('[data-i18n]').forEach(el => {
    const i18nKey = el.getAttribute('data-i18n');
    let translatedText = Granite.I18n.get(i18nKey);
    
    // 处理带参数的翻译项(比如包含占位符的文本)
    if (el.hasAttribute('data-i18n-args')) {
      try {
        const args = JSON.parse(el.getAttribute('data-i18n-args'));
        translatedText = Granite.I18n.get(i18nKey, args);
      } catch (err) {
        console.error('解析i18n参数失败:', err);
      }
    }
    
    // 更新元素内容
    el.textContent = translatedText;
    
    // 如果是placeholder等属性,也需要更新
    if (el.hasAttribute('data-i18n-placeholder')) {
      const placeholderKey = el.getAttribute('data-i18n-placeholder');
      el.setAttribute('placeholder', Granite.I18n.get(placeholderKey));
    }
  });
}

这个方案适合纯前端渲染的翻译内容,无需刷新页面,响应快。

方案二:跳转到对应语言的页面路径

如果页面有大量后端渲染的内容(比如组件初始HTML中的文本),仅前端更新无法覆盖这些内容,最稳妥的方式是跳转到对应语言的站点路径:

document.getElementById('language-select').addEventListener('change', function(e) {
  const newLocale = e.target.value;
  // 构建对应语言的页面URL
  const currentPath = window.location.pathname;
  // 假设当前路径是/content/mysite/en/home.html,替换en为新locale
  const newPath = currentPath.replace(/\/content\/[^\/]+\/[^\/]+/, `/content/mysite/${newLocale}`);
  // 跳转刷新页面
  window.location.href = newPath;
  // 可选:持久化用户选择
  localStorage.setItem('preferredLocale', newLocale);
});

这种方式让AEM从后端重新渲染对应语言的页面,所有内容(包括后端生成的文本)都会更新,体验更完整。

额外优化:持久化用户语言偏好

把用户选择的语言存在localStorage或cookie中,页面加载时自动应用:

window.addEventListener('DOMContentLoaded', () => {
  const savedLocale = localStorage.getItem('preferredLocale');
  if (savedLocale) {
    // 方式一:前端更新文本
    Granite.I18n.setLocale(savedLocale);
    refreshTranslatedContent();
    
    // 方式二:如果需要后端渲染,可判断当前路径是否匹配,不匹配则跳转
    // const currentLocale = window.location.pathname.split('/')[3];
    // if (currentLocale !== savedLocale) {
    //   const newPath = window.location.pathname.replace(`/${currentLocale}/`, `/${savedLocale}/`);
    //   window.location.href = newPath;
    // }
  }
});

注意事项

  • 确保所有需要翻译的元素都正确添加了data-i18n属性,这是AEM前端i18n的标准用法。
  • 对于带参数的翻译,要正确设置data-i18n-args属性(值为JSON格式的数组)。
  • 如果使用组件的后端渲染内容,优先选择跳转对应语言路径的方案,避免前端后端内容不一致。

内容的提问来源于stack exchange,提问作者daitienshi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.22 10:09:11