页面元数据的本地化
设置本地化的 <title> 和 <description> 标签
问题
用户在浏览页面时选择了西班牙语,所有可见内容都已正确翻译。然而,浏览器标签页和搜索引擎结果摘要仍然显示英文标题和描述。这种元数据不一致会导致用户体验混乱,并因在搜索中展示无关信息而影响 SEO 效果。
解决方案
在页面和布局中使用 Next.js 的 generateMetadata 函数。该服务端函数可以根据 lang 参数加载正确的翻译(与组件中加载字典的逻辑一致),并返回包含本地化标题和描述的动态 metadata 对象。
步骤
1. 创建加载字典的函数
你需要在服务端加载扁平翻译文件的方法。为此创建一个辅助函数。
// app/get-dictionary.ts
import 'server-only';
type Messages = Record<string, string>;
const dictionaries: { [key: string]: () => Promise<Messages> } = {
en: () => import('@/dictionaries/en.json').then((module) => module.default),
es: () => import('@/dictionaries/es.json').then((module) => module.default),
};
export const getDictionary = async (lang: string) => {
const load = dictionaries[lang];
if (load) {
return load();
}
return dictionaries.en();
};
2. 在页面中定义元数据
在你的页面文件(例如 app/[lang]/about/page.tsx)中,导出一个名为 async 的函数。Next.js 在渲染页面时会自动调用它。
// app/[lang]/about/page.tsx
import { getDictionary } from '@/app/get-dictionary';
import type { Metadata } from 'next';
type Props = {
params: { lang: string };
};
// This function generates metadata
export async function generateMetadata({ params }: Props): Promise<Metadata> {
// Load the dictionary for this page
const dict = await getDictionary(params.lang);
return {
title: dict['about.title'], // e.g., "About Us" or "Sobre Nosotros"
description: dict['about.description'],
};
}
// The rest of your page component
export default function AboutPage() {
return (
<div>
{/* Page content */}
<h1>...</h1>
</div>
);
}
3. 在根布局中设置标题模板
为避免在每个标题中重复站点名称,可以在根布局中设置模板。
// app/[lang]/layout.tsx
import { getDictionary } from '@/app/get-dictionary';
import type { Metadata } from 'next';
type Props = {
params: { lang: string };
children: React.ReactNode;
};
// You can generate metadata in layouts too
export async function generateMetadata({ params }: Props): Promise<Metadata> {
const dict = await getDictionary(params.lang);
return {
// This provides a base title and a template
title: {
default: dict['site.name'], // e.g., "My Awesome Site"
template: `%s | ${dict['site.name']}`, // e.g., "About Us | My Awesome Site"
},
description: dict['site.description'],
};
}
export default async function RootLayout({ children, params }: Props) {
// ... rest of your layout (loading providers, etc.)
return (
<html lang={params.lang}>
<body>{children}</body>
</html>
);
}