最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Svelte head title suffix - Stack Overflow

programmeradmin2浏览0评论

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: .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?

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?

Share Improve this question asked Oct 29, 2019 at 11:13 SoullivaneuhSoullivaneuh 3,8633 gold badges43 silver badges80 bronze badges
Add a comment  | 

3 Answers 3

Reset to default 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>

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>

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()
发布评论

评论列表(0)

  1. 暂无评论