Sanity本地化:使用documentInternationalization过滤引用内容问题求助
Sanity本地化引用字段过滤问题修复
现有代码的问题
- 硬编码
_type为catTreat,无法匹配引用列表中的dogTreat类型 - 错误使用
slug.current匹配语言,应该直接用你已配置的language字段 - 字符串拼接方式存在语法风险,且参数传递逻辑错误
修正后的代码
defineField({ name: 'product', type: 'array', of: [{ type: 'reference', to: [{type: 'dogTreat'}, {type: 'catTreat'}] }], options: { filter: ({ document }) => { // 防止当前文档未设置language字段导致过滤异常 if (!document?.language) return { filter: 'false' }; return { // 同时兼容两种零食类型,且匹配当前文档的语言 filter: `(_type == "dogTreat" || _type == "catTreat") && language == $language`, params: { language: document.language } }; } }, group: 'products', }),
关键说明
- 先校验
document.language是否存在,避免未定义值引发的查询错误 - 过滤条件同时包含
dogTreat和catTreat两种类型,确保下拉列表能显示两种同语言产品 - 使用参数化查询
$language替代字符串拼接,既符合Sanity的查询规范,又避免语法错误 - 确认
dogTreat和catTreatSchema中确实存在language字段(你已配置,此步为二次校验)
内容的提问来源于stack exchange,提问作者shubham tarpara
相关产品推荐
相关产品推荐

