Usage question - override default values with new values set by child page / layout
TristanBrotherton opened this issue · 8 comments
Is there a recommended way to use this component such that it could be integrated with a default set of values, that could then be overridden by a child page with new values if (and only if) they were set?
If you are using SvelteKit, we recommend writing as follows
+layout.svelte
<script>
import { MetaTags } from 'svelte-meta-tags';
import { page } from '$app/stores';
export let data;
$: metaTags = {
titleTemplate: '%s | Svelte Meta Tags',
...$page.data.metaTagsChild,
};
</script>
{#if metaTagsChild}
<MetaTags {...metaTags} />
{/if}
+page.ts
import type { MetaTagsProps } from 'svelte-meta-tags';
export const load = async ({ url }) => {
const metaTags: MetaTagsProps = Object.freeze({
title: 'page title',
description: 'Description',
openGraph: {
type: 'website',
url: new URL(url.pathname, url.origin).href,
locale: 'en_IE',
title: 'Open Graph Title',
description: 'Open Graph Description',
},
});
return {
metaTagsChild,
};
};
Thank you. Would you accept a PR with this added to the documentation?
Yes! PR please.
PR added - closing this for hygiene, thank you!
@oekazuma, hi! First of all, thanks for the project! It's quite handy and I use it in my SvelteKit project.
I have a minor question regarding this exact use case:
Do I need to do Object.freeze
in load function? Or it's just a personal preference?
It seems like this works fine too:
import type { MetaTagsProps } from 'svelte-meta-tags';
export const load = async ({ url }) => {
const metaTags: MetaTagsProps = {
title: 'page title',
description: 'Description',
openGraph: {
type: 'website',
url: new URL(url.pathname, url.origin).href,
locale: 'en_IE',
title: 'Open Graph Title',
description: 'Open Graph Description',
},
};
return {
metaTagsChild: metaTags,
};
};
Maybe I'm missing something.
@fromaline
It is safe to use Object.freeze
to prevent changes from being made to the object. It is up to the user whether to use it or not, but I personally recommend it.
I have prepared an example of its use, so please take a look at it here.
https://github.com/oekazuma/svelte-meta-tags/tree/main/example/src/routes
@oekazuma got it. Thanks for answering!
Your example looks good to me. Maybe we should replace the current "Overwriting default values with a child page" section with code from your example?
@fromaline
We have already updated the documentation!
https://github.com/oekazuma/svelte-meta-tags?tab=readme-ov-file#-usage