Soullivaneuh
Soullivaneuh

Reputation: 3863

Svelte head title suffix

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:

How can an achieve what I want to do?

Upvotes: 10

Views: 4015

Answers (3)

Daniel Miedzik
Daniel Miedzik

Reputation: 51

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()

Upvotes: 4

parker_codes
parker_codes

Reputation: 3397

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>

Upvotes: 6

Tholle
Tholle

Reputation: 112807

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>

Upvotes: 9

Related Questions