Svelte head title suffix
Asked Answered
F

3

10

I want to add a head title suffix like - mywebsite on each Svelte page.

I'm struggling finding how to do it with ease and simplicity.

On the svelte website source, we can see they do it manually: https://github.com/sveltejs/svelte/blob/1273f978084aaf4d7c697b2fb456314839c3c90d/site/src/routes/docs/index.svelte#L15

I started creating a component like this:

<script>
  export let title = false;
</script>

<svelte:head>
  <title>
    {#if title}
      {title} • WebSite
    {:else}
      Website • Home suffix
    {/if}
  </title>
</svelte:head>

But:

  • I have a <title> can only contain text and {tags}svelte(illegal-structure) error
  • I'm not sure it's the easiest way.

How can an achieve what I want to do?

Fourpenny answered 29/10, 2019 at 11:13 Comment(0)
B
9

Since <title> only can contain text or {tags} you could compute the document title with the ternary operator.

Example

<script>
  export let title = false;
</script>

<svelte:head>
  <title>{title ? `${title} • WebSite` : 'Website • Home suffix'}</title>
</svelte:head>
Blur answered 29/10, 2019 at 11:40 Comment(4)
So create a title component to import on every page is the best solution? Nothing more simple/buit-in?Fourpenny
If you're making an SPA or using Sapper then you can keep the <svelte:head> in your top component and update it programmaticallyReflux
@BennyHinrichs are you suggesting to create a title.js file to make it? In that case, it is not better than creating a component, am I wrong?Fourpenny
In Sapper, you would just put the title logic in your _layout.svelte file. See the docs and an example in sapper-template.Reflux
C
6

While using a ternary inside of the markup works just fine, reactivity statements may help clean it up:

<script>
  export let title = false;

  $: fullTitle = title 
        ? `${title} • WebSite` 
        : 'Website • Home suffix';
</script>

<svelte:head>
  <title>{fullTitle}</title>
</svelte:head>
Crosley answered 29/10, 2019 at 15:36 Comment(0)
T
4

You can also use small store for this. Here you can find REPL example:
https://svelte.dev/repl/b604a75a8a344527a39f10cab7b7ee66?version=3.32.0

import { writable } from 'svelte/store';

function createTitle() {
    const {subscribe, set, update} = writable('');
    
    return {
        subscribe,
        set: (value) => {
            set(`${value} • WebSite`)
        },
        clear: () => {
            set('Website • Home suffix');
        }
    }
}

export const title = createTitle();

Then when you want set new title you can use:

title.set('page title')

Store will add suffix automatically...

If you want display main title call:

title.reset()
Targum answered 26/1, 2021 at 9:38 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.