Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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:

  • 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?

like image 815
Soullivaneuh Avatar asked Oct 29 '19 11:10

Soullivaneuh


2 Answers

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>
like image 190
Tholle Avatar answered Oct 06 '22 06:10

Tholle


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>
like image 25
parker_codes Avatar answered Oct 06 '22 08:10

parker_codes