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

SSR模式下如何让框架组件及脚本访问Astro.currentLocale?

在Astro SSR中让全局脚本/框架组件访问Astro.currentLocale的简洁方案

下面是几个无需逐层传递props的可行方案,适配SSR场景:

方案1:全局变量注入(服务端+客户端通用)

在根布局文件(比如src/layouts/Layout.astro)中,将Astro.currentLocale同时注入服务端的globalThis和客户端的window对象:

---
// 服务端环境下注入全局对象
globalThis.__CURRENT_LOCALE__ = Astro.currentLocale;
---

<!DOCTYPE html>
<html lang={Astro.currentLocale}>
  <head>
    <!-- 客户端环境下注入window,用is:inline确保脚本直接渲染 -->
    <script is:inline>
      window.__CURRENT_LOCALE__ = "{Astro.currentLocale}";
    </script>
  </head>
  <body>
    <slot />
  </body>
</html>

之后在任意工具脚本或框架组件中,就可以通过统一的工具函数获取locale:

// src/utils/getLocale.js
export const getCurrentLocale = () => {
  return typeof window !== 'undefined' 
    ? window.__CURRENT_LOCALE__ 
    : globalThis.__CURRENT_LOCALE__;
};

这个方案完全避开了客户端依赖window.location的问题,SSR渲染时框架组件能直接拿到服务端注入的正确locale。

方案2:结合框架全局状态管理

如果使用React/Vue这类框架,可以借助它们的全局状态能力,在根布局中注入locale初始值:

React示例:

  1. 创建Locale Context:
// src/contexts/LocaleContext.jsx
import { createContext, useContext } from 'react';

export const LocaleContext = createContext();
export const useLocale = () => useContext(LocaleContext);
  1. 在根布局中包裹组件:
---
import { LocaleContext } from '../contexts/LocaleContext';
---

<html lang={Astro.currentLocale}>
  <body>
    <LocaleContext.Provider value={Astro.currentLocale}>
      <slot />
    </LocaleContext.Provider>
  </body>
</html>
  1. 任意React组件中直接调用:
import { useLocale } from '../contexts/LocaleContext';

export default function MyComponent() {
  const locale = useLocale();
  return <div>当前语言:{locale}</div>;
}

SSR时初始值由服务端的Astro.currentLocale提供,客户端会自动继承该值,无需从路径提取。

方案3:利用Astro中间件传递Locale

创建src/middleware.js,将locale挂载到请求上下文的locals对象:

import { defineMiddleware } from 'astro:middleware';

export const onRequest = defineMiddleware((context, next) => {
  // 直接从Astro上下文获取当前locale
  context.locals.currentLocale = Astro.currentLocale;
  return next();
});

之后在.astro文件中,可以将Astro.locals.currentLocale作为props传递给框架组件的入口节点,后续组件可通过框架状态管理(如Context)分发,避免逐层传递。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.21 00:59:55