在Sanity中为String类型字段创建动态initialValue



我在Sanity中有一个文档。有三个字段- title (string), slug (slug)和path (string)。

如何在路径字段上使用initialValue来显示基于slug值的自定义动态字符串?

例如,如果slug的值是my-new-path,我如何动态地将路径字段的initialvalue设置为/blog/events/my-new-path?

export default {
name: "myPage",
title: "My Page",
type: "document",
fields: [
{
name: "title",
type: "string",
title: "Page Title",
validation: (Rule) => Rule.required(),
},
{
name: "slug",
type: "slug",
title: "Slug",
options: {
source: "title",
maxLength: 200, // will be ignored if slugify is set
slugify: (input) =>
input
.slice(0, 200)
.toLowerCase()
//Remove spaces
.replace(/s+/g, "-")
//Remove special characters
.replace(/[&/\#,+()$~%.'`’":*?<>{}]/g, ""),
},
validation: (Rule) => Rule.required(),
},
{
name: "path",
type: "string",
title: "URL Path",
readOnly: true,
},
]
}

我认为你能做的是为你的段塞使用异步slugifier,并在生成段塞时使用客户端来修补文档。

import slugify from 'some-off-the-shelf-slugifier'
async function myAsyncSlugifier(input, schemaType, context) {
const slug = slugify(input)
const {document, getClient} = context
const client = getClient({apiVersion: '2022-12-07'})
try {
const patch = await client
.patch(document._id)
.set({path: `/foo/bar/${slug}`})
.commit()
} catch(e) {
console.log(e)
}


return slug
}
//…
// schema field
{
title: 'Slug',
name: 'slug',
type: 'slug',
options: {
source: 'title',
slugify: myAsyncSlugifier
}
}

最新更新