ترجمة البيانات الوصفية للصفحة
تعيين وسوم <title> و <description> المترجمة
المشكلة
يشاهد المستخدم صفحة باللغة الإسبانية، وجميع المحتوى المرئي مترجم بشكل صحيح. ومع ذلك، لا تزال علامة تبويب المتصفح ومقتطف نتيجة محرك البحث يعرضان العنوان والوصف باللغة الإنجليزية. يؤدي عدم تطابق البيانات الوصفية هذا إلى تجربة مستخدم مربكة ويضر بتحسين محركات البحث من خلال تقديم معلومات غير ذات صلة في البحث.
الحل
استخدم دالة generateMetadata في Next.js ضمن صفحاتك وتخطيطاتك. يمكن لهذه الدالة من جانب الخادم تحميل الترجمات الصحيحة بناءً على معامل 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 تسمى generateMetadata. سيستدعي 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>
);
}