首頁 > web前端 > js教程 > 主體

Sanity CMS - 關於它

Mary-Kate Olsen
發布: 2024-10-12 22:27:02
原創
821 人瀏覽過

Sanity CMS - All About It

這裡深入解釋了Sanity 的關鍵概念以及如何將其與Next.jsReact.js 等前端框架一起使用


1. 理智內容工作室

Content Studio 是您直覺管理內容的地方。它是可自訂的,並使用 React 構建,使其能夠靈活地為各種類型的內容創建不同的資料結構。

如何設定:

  1. 安裝 Sanity CLI:
   npm install -g @sanity/cli
登入後複製
  1. 初始化一個 Sanity 專案:
   sanity init
登入後複製

依照指示選擇項目範本並選擇設定(項目名稱、資料集等)。

  1. 啟動內容工作室:
   sanity start
登入後複製
登入後複製

這將在 http://localhost:3333 開啟內容工作室。您現在可以在這裡管理您的內容。

2. 架構

Sanity 中的模式定義內容的結構,類似於在資料庫中定義模型。您將在 Sanity 專案的 schemas 資料夾中定義模式。

範例:建立部落格架構

  1. 在 schemas 資料夾中建立一個 schema 檔案 blog.js :
   export default {
     name: 'blog',
     title: "'Blog Post',"
     type: 'document',
     fields: [
       {
         name: 'title',
         title: "'Title',"
         type: 'string',
       },
       {
         name: 'body',
         title: "'Body',"
         type: 'portableText', // For rich text fields
       },
       {
         name: 'author',
         title: "'Author',"
         type: 'reference',
         to: [{ type: 'author' }], // Reference to another document type
       },
       {
         name: 'publishedAt',
         title: "'Published At',"
         type: 'datetime',
       },
     ],
   };
登入後複製
  1. 將架構加入到 schema.js:
   import blog from './blog';
   export default createSchema({
     name: 'default',
     types: schemaTypes.concat([blog]),
   });
登入後複製
  1. 重新啟動工作室以載入新架構:
   sanity start
登入後複製
登入後複製

此架構建立部落格文章的結構,包括標題、正文、作者參考和發布日期的欄位。


3. 文件

文件是 Sanity 中的內容條目。定義架構後,您可以在 Content Studio 中根據這些架構建立文件。

如何在 Studio 中建立文件:

  1. 開啟您的Sanity Studio (http://localhost:3333)。
  2. 從側邊欄中選擇「部落格文章」(或您的架構名稱)。
  3. 填寫表格內容(例如標題、正文和作者)並點擊發布

4. 手提文字

便攜式文字是 Sanity 靈活的富文本編輯器,它允許您定義不同的文字元素(如圖像、標題或自訂元件)在內容中的顯示方式。

在架構中使用可移植文字:

  1. 在您的架構中,將欄位指定為類型:「portableText」。
  2. 您可以擴展可移植文字以包含自訂區塊:
   export default {
     name: 'body',
     title: 'Body',
     type: 'array',
     of: [
       { type: 'block' }, // Basic block elements like paragraphs
       { type: 'image' }, // Custom image blocks
     ],
   };
登入後複製

5. 理智客戶端

Sanity 用戶端在前端框架(如 React 或 Next.js)中使用,用於從 Sanity 取得內容。它使用 GROQ,一種專門為 Sanity 設計的查詢語言。

安裝理智客戶端:

在您的 Next.jsReact.js 專案中,安裝 Sanity 用戶端:

npm install @sanity/client @sanity/image-url
登入後複製

設定 Sanity 客戶端:

  1. 在前端專案中建立 sanity.js 檔案來設定客戶端:
   import sanityClient from '@sanity/client';

   export const client = sanityClient({
     projectId: 'yourProjectId', // found in sanity.json or sanity studio
     dataset: 'production',
     apiVersion: '2023-01-01', // use a specific API version
     useCdn: true, // 'false' if you want the latest data
   });
登入後複製

GROQ 查詢範例:

要取得部落格文章,請與客戶端一起使用 GROQ:

import { client } from './sanity';

const query = `*[_type == "blog"]{title, body, publishedAt}`;
const blogs = await client.fetch(query);
登入後複製

您現在已取得所有部落格文章,並且可以在 Next.js 或 React 元件中呈現它們。


6. 影像處理

Sanity 提供強大的影像處理功能,讓您輕鬆裁切、調整大小和最佳化影像。

使用圖像 URL 進行轉換:

  1. 安裝@sanity/image-url 套件:
   npm install @sanity/image-url
登入後複製
  1. 設定圖像 URL 生成器:
   import imageUrlBuilder from '@sanity/image-url';
   import { client } from './sanity';

   const builder = imageUrlBuilder(client);

   export function urlFor(source) {
     return builder.image(source);
   }
登入後複製
  1. 在 Next.js 或 React 元件中使用:
   import { urlFor } from './sanity';

   const Blog = ({ blog }) => (
     <div>
       <h1>{blog.title}</h1>
       <img src={urlFor(blog.image).width(800).url()} alt="Blog Image" />
     </div>
   );
登入後複製

此範例展示如何從 Sanity 產生最佳化的圖像 URL 以在元件中渲染。


7. 資料關係

您可以使用引用類型在 Sanity 中建立文件之間的關係。這對於連結部落格作者及其帖子等數據非常有用。

範例:部落格文章架構中的作者參考

{
  name: 'author',
  title: 'Author',
  type: 'reference',
  to: [{ type: 'author' }]
}
登入後複製

在內容工作室中,您可以在建立部落格文章時選擇作者文件作為參考。


8. 即時協作

Sanity 提供即時協作,多個使用者可以同時處理同一個文件。所有處理內容的使用者都會立即看到變更。

此功能可自動內建於 Sanity Studio 中,您無需進行任何特殊設定即可啟用它。


9. 將 Sanity 與 Next.js/React.js 整合

要將 Sanity 與 Next.jsReact.js 專案集成,請按照以下步驟操作:

Example: Fetch Blog Data in Next.js

  1. Use getStaticProps to fetch Sanity data at build time:
   import { client } from '../sanity';

   export async function getStaticProps() {
     const blogs = await client.fetch(`*[_type == "blog"]`);
     return {
       props: { blogs },
     };
   }

   const BlogList = ({ blogs }) => (
     <div>
       {blogs.map(blog => (
         <div key={blog._id}>
           <h2>{blog.title}</h2>
           <p>{blog.body[0]?.children[0]?.text}</p>
         </div>
       ))}
     </div>
   );

   export default BlogList;
登入後複製
  1. In React.js, use useEffect to fetch data dynamically:
   import { client } from './sanity';
   import { useState, useEffect } from 'react';

   const BlogList = () => {
     const [blogs, setBlogs] = useState([]);

     useEffect(() => {
       const fetchBlogs = async () => {
         const data = await client.fetch(`*[_type == "blog"]`);
         setBlogs(data);
       };
       fetchBlogs();
     }, []);

     return (
       <div>
         {blogs.map(blog => (
           <div key={blog._id}>
             <h2>{blog.title}</h2>
             <p>{blog.body[0]?.children[0]?.text}</p>
           </div>
         ))}
       </div>
     );
   };

   export default BlogList;
登入後複製

Summary:

  • Sanity Studio: Manage content visually and customize data structure with schemas.
  • Schemas: Define content structure (documents, objects, references).
  • Portable Text: Flexible rich text editor with support for custom components.
  • Sanity Client: Fetch content using GROQ in React/Next.js.
  • Image Handling: Easily generate optimized image URLs.
  • Data Relationships: Link documents using references.
  • Real-Time Collaboration: Built-in for team workflows.

This setup allows you to efficiently manage, query, and display content in front-end frameworks like Next.js and React.js.

以上是Sanity CMS - 關於它的詳細內容。更多資訊請關注PHP中文網其他相關文章!

來源:dev.to
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
作者最新文章
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!