How to change page title dynamically in Sveltekit?
Asked Answered
P

3

30

I'm learning SvelteKit and this might be a very elementary question. But I could not figure out how to change the tab's title.

In my src/+layout.svelte I have:

    <script>
        let title="My Site Homepage"
    
    </script>
    <head>
        <meta charset="UTF-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        ...
      <title>{title}</title>
  
   </head>

Then in my /src/faq/+page.svelte I'd like to change the title to 'FAQ'

So I put

<script>
    let title="FAQ"        
</script>

But when I visit http://localhost:5173/faq the tab's title is not changed. So I'm wondering how can I do that? Is there an idomatic way to do so?

Plankton answered 29/10, 2022 at 8:0 Comment(1)
If you want to enforce a certain format for titles (like Page title | Website name) and not want to add the second bit every page you could use a store. If you just need to change the title based on what happens in the page you can just use a variable for that page.Sousaphone
P
47

Well, thanks svelte docs, I found my answer.

The svelte:head element allows you to insert elements inside the <head> of your document:

So I just need to add this to FAQ page:

<svelte:head>
    <title>FAQ</title> 
</svelte:head>
Plankton answered 29/10, 2022 at 8:18 Comment(1)
I think you also need %sveltekit.head% in your app.html file, but any scaffolding should have already done that for youMerchandise
B
7

From my understanding you want to change the title as go.

To get this I don't suggest using two way binding, since 'variable' you are inputting to bind is not actually a variable but a space box which is functioned for binding. Just pass the title and it might work.

Since people need direct answers instead of explaining the issues.

//../components/meta-title.svelte

<svelte:head>
   <title>{title}</title>
</svelte:head>

<script>
   export let title = "default title for page"
</script>


//../pages/_layout.svelte

<Meta title="This is a dynamic title" />

Let me know if it doesn't work.

Thank you

Bosanquet answered 29/10, 2022 at 8:7 Comment(0)
A
1

Inside the main +layout.svelte file you could use the page store:

<script>
    //...
    import { page } from "$app/stores";

    const appName = "My App";
    $: title = [appName, ...$page.url.pathname.split("/").slice(1)].filter(Boolean).join(" - ");
</script>

<svelte:head>
    <title>{title}</title>
</svelte:head>

will result for example in:

Route Title
/ My App
/about My App - about
/products/345 My App - products - 345
Annecorinne answered 15/5 at 9:26 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.