向 Next.js 项目添加元标题和描述

问题描述 投票:0回答:1

在我的 Next.js 项目中,我在

/utils/content/
文件夹中编写了数十页代码。

我将所有页面逐一包含在

content.jsx
文件中,然后将
content.jsx
文件导入到
page.js
文件中。

export const pageContent = {
  ...homeContent,                               // /
  ...aboutContent,                              // /about
  ...whoWeAreContent,                           // /about/who-we-are
  ...usContent,                                 // /about/who-we-are/us
  // all the URLs listed (imported) here
}

这是我的应用程序文件夹的文件夹结构。

这是我的

page.js
文件:

"use client";
export default function CatchAll() {
  const pathname = usePathname();
  const blocks = pageContent?.[pathname];

  return (
    <>
      {!blocks ? (
        notFound()
      ) : (
        <>
          {blocks.map((block, index) => (
            <block.component {...block.componentProps} key={index}>
              {block.content}
            </block.component>
          ))}
        </>
      )}
    </>
  );
}

现在,我想为项目中的每个页面添加不同的元标题和描述。我该怎么办?

next.js seo metadata next.js13
1个回答
0
投票

在 pageContent 中您可以执行以下操作:

export const pageContent = {
  "/": {
    content: [...homeContent],  // Content blocks for home page
    meta: {
      title: "Home Page Title",
      description: "Description for the home page."
    }
  },
  "/about": {
    content: [...aboutContent],  // Content blocks for about page
    meta: {
      title: "About Page Title",
      description: "Description for the about page."
    }
  },
  // Other pages with their respective content and metadata
};

然后更新 CatchAll 组件以检索并使用当前页面的元数据:

"use client";

export default function CatchAll() {
  const pathname = usePathname();
  const page = pageContent?.[pathname];

  useEffect(() => {
    if (page && page.meta) {
      document.title = page.meta.title; // Set document title
      // Optionally update other meta tags dynamically here
      // Example: document.querySelector('meta[name="description"]').setAttribute("content", page.meta.description);
    }
  }, [page]);

  const blocks = page?.content;

  return (
    <>
      {!blocks ? (
        notFound()
      ) : (
        <>
          {blocks.map((block, index) => (
            <block.component {...block.componentProps} key={index}>
              {block.content}
            </block.component>
          ))}
        </>
      )}
    </>
  );
}
© www.soinside.com 2019 - 2024. All rights reserved.