问题可以在这里看到
我在前端使用Sanity无头 CMS 和 GatsbyJS构建了一个站点。
我正在动态查询 URL,以便它可以在src
属性内呈现</iframe>
问题是当用户添加一个包含 的 URL 时&
,这对于 Google 日历的嵌入代码非常常见。
随着&
链接不再有效并且日历中断(变为空白)。除非我直接在src
其中硬编码它,这正是我们想要避免的。
我怎样才能减轻/逃避这个问题并拥有它,以便我可以相应地呈现 URL?
我研究过encodeURI
, encodeURIComponent
,甚至尝试过这个自定义函数:
function htmlEntities(str) {
return String(str).replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"');
}
没有骰子...
- 如果可能的话,在 Sanity 的生态系统中寻找客户端 JS 解决方案或后端解决方案
我目前的实现
// sanity schema
export default {
type: 'document',
title: 'Google Calendar',
name: 'calendar',
fields: [
{
type: 'string',
name: 'Title',
},
{
type: 'url',
name: 'URL',
validation: (Rule) => Rule.required(),
},
],
};
//gastby
export default function GoogleCalendar() {
const { calendar } = useStaticQuery(graphql`
query {
calendar: allSanityCalendar {
nodes {
URL
Title
}
}
}
`);
if (!calendar.nodes.length) return null;
return (
<>
<div>
{calendar.nodes.map((node) => (
<iframe
src={node.URL}
id="test"
title={node.Title}
width="100%"
height="1000px"
async
/>
))}
</div>
</>
);
}
这是一个说明问题的沙箱: https ://stackblitz.com/edit/iframe-dynamic-src