Skip to content

Instantly share code, notes, and snippets.

@arcataroger
Created December 6, 2024 00:36
Show Gist options
  • Save arcataroger/cf797380440164dafd73cd2cbdf27c0a to your computer and use it in GitHub Desktop.
Save arcataroger/cf797380440164dafd73cd2cbdf27c0a to your computer and use it in GitHub Desktop.
DehydratedHead.svelte
<script lang="ts" context="module">
export interface TitleMetaLinkTag {
/** the tag for the meta information */
tag: string;
/** the inner content of the meta tag */
content?: string | null | undefined;
/** the HTML attributes to attach to the meta tag */
attributes?: Record<string, string> | null | undefined;
}
export interface SeoTitleTag {
tag: 'title';
content: string | null;
attributes?: null;
}
export interface RegularMetaAttributes {
name: string;
content: string;
}
export interface OgMetaAttributes {
property: string;
content: string;
}
export interface SeoMetaTag {
tag: 'meta';
content?: null;
attributes: RegularMetaAttributes | OgMetaAttributes;
}
export interface FaviconAttributes {
sizes: string;
type: string;
rel: string;
href: string;
}
export interface AppleTouchIconAttributes {
sizes: string;
rel: 'apple-touch-icon';
href: string;
}
export interface SeoLinkTag {
tag: 'link';
content?: null;
attributes: FaviconAttributes | AppleTouchIconAttributes;
}
export type SeoTag = SeoTitleTag | SeoMetaTag;
export type FaviconTag = SeoMetaTag | SeoLinkTag;
export type SeoOrFaviconTag = SeoTag | FaviconTag;
</script>
<script lang="ts">
export let data: Array<TitleMetaLinkTag | SeoOrFaviconTag> = [];
// Statically output HTML instead of using conditionals inside <svelte:head>
const renderedTags = data
.map(({ tag, attributes, content }) => {
const attrs = attributes
? Object.entries(attributes)
.map(([key, value]) => `${key}="${value}"`)
.join(' ')
: '';
if (content) {
return `<${tag} ${attrs}>${content}</${tag}>`;
} else {
return `<${tag} ${attrs} />`;
}
})
.join('\n');
</script>
<svelte:head>
{@html renderedTags}
</svelte:head>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment