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

如何在Docusaurus页面中检测当前语言并使用JS展示动态内容

Docusaurus多语言动态内容实现方案

给你几个实用的实现方式,能直接在页面里写JS逻辑判断当前语言,灵活处理长HTML内容:

1. 用官方的useTranslation钩子(推荐)

Docusaurus自带的useTranslation钩子能直接获取当前语言环境,不管是简单标题还是复杂HTML都能轻松处理:

import { useTranslation } from '@docusaurus/useTranslation';

function MyCustomPage() {
  const { i18n } = useTranslation();
  // 动态判断标题
  const pageTitle = i18n.currentLocale === 'en' ? 'en title' : 'zh title';
  
  // 处理长HTML内容,直接用条件渲染
  const pageContent = i18n.currentLocale === 'en' ? (
    <div className="content-block">
      <h2>About This Feature</h2>
      <p>This is a detailed introduction in English, with multiple paragraphs and HTML elements.</p>
      <ul>
        <li>English list item 1</li>
        <li>English list item 2</li>
      </ul>
    </div>
  ) : (
    <div className="content-block">
      <h2>功能介绍</h2>
      <p>这是一段包含多个段落和HTML元素的中文详细说明。</p>
      <ul>
        <li>中文列表项1</li>
        <li>中文列表项2</li>
      </ul>
    </div>
  );

  return (
    <div>
      <h1>{pageTitle}</h1>
      {pageContent}
    </div>
  );
}

export default MyCustomPage;

2. 直接访问全局上下文变量

如果是在MDX页面里直接写逻辑,不用单独写组件,可以直接访问全局的__docusaurus.context.i18n变量:

---
title: Dynamic Page
---

import React from 'react';

const currentLocale = typeof window !== 'undefined' ? window.__docusaurus.context.i18n.currentLocale : 'en';
const dynamicTitle = currentLocale === 'en' ? 'en title' : 'zh title';

# {dynamicTitle}

{currentLocale === 'en' ? (
  <div>
    <p>Here's your long English content with <strong>bold text</strong> and other HTML tags.</p>
    <p>Another paragraph for English users.</p>
  </div>
) : (
  <div>
    <p>这是给中文用户的长内容,包含<strong>加粗文本</strong>和其他HTML标签。</p>
    <p>中文内容的第二段。</p>
  </div>
)}

3. 抽成复用组件(适合多处使用的长内容)

如果同一段多语言内容要在多个页面用,可以把它封装成组件,方便复用:

// src/components/MultiLangIntro.js
import { useTranslation } from '@docusaurus/useTranslation';

export default function MultiLangIntro() {
  const { i18n } = useTranslation();
  
  if (i18n.currentLocale === 'en') {
    return (
      <div className="intro-section">
        <h3>Welcome to Our Site</h3>
        <p>We're glad you're here! This is a longer introduction that appears across multiple pages.</p>
      </div>
    );
  }
  
  return (
    <div className="intro-section">
      <h3>欢迎访问我们的站点</h3>
      <p>很高兴您能来!这段较长的介绍会在多个页面展示。</p>
    </div>
  );
}

然后在MDX或页面组件里导入使用:

import MultiLangIntro from '@site/src/components/MultiLangIntro';

<MultiLangIntro />

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 19:05:46