Svelte SEO - Dynamic page title

88 views Asked by At

First off, I have already checked this question, but it does not really answer my own question.

Here is my situation:

  • I have a main page (+page.svelte, in the same folder as +layout.svelte) and a few extra pages (+page.svelte, located in subfolders);
  • +layout.svelte uses SvelteSEO which contains a number of tags, including a "title" tag which is currently a simple string;
  • I have already tweaked SvelteSEO by using {$page.url.pathname} to make the "canonical" tag dynamic (it's set to: "https://example.com{$page.url.pathname}") and it works well when I deploy.

What I want to do now is tweak the "title" tag to make it dynamic, so that each page would be something like "Example | Page title".

What I have tried:

  • Adding "export let title = "Example | Page title X" to the script of page X;
  • Adding "import { title } from 'path to Page X'" in +layout.svelte;
  • Using the "title" tag in the SvelteSEO part of +layout.svelte.

However, that's not working and I am not sure what I can do. Spoiler: I am still a bit of a noob and I am mostly tweaking a website that was designed by a developer, so I still have a lot to learn!

Thanks!

1

There are 1 answers

3
Corrl On

One way would be to set the title dynamically inside +layout.svelte based on the $page.url.pathname and a 'lookup' function or object

<script>
    import {page} from '$app/stores'
    import SvelteSeo from "svelte-seo";

    function getPageTitle(pathname) {
        switch(pathname) {
            case '/' :
                return 'Home'
            case '/about':
                return 'About'
            default:
                return 'Default title'
        }
    }
</script>

<SvelteSeo
    title={getPageTitle($page.url.pathname)}
    ...
    />
<script>
    import {page} from '$app/stores'
    import SvelteSeo from "svelte-seo";

    const pageTitle = {
        '/' :   'Home',
        '/about': 'About',
    }
</script>

<SvelteSeo
    title={pageTitle[$page.url.pathname] ?? 'Default title'}
    ...
    />