Melitele
Melitele

Reputation: 35

Dynamically change translated page title - Svelte

I've made a page in Svelte. I've provided translations in two languages and it works fine. Now, I want the title on each page to change, and what's more, I want it translated into the current language of the page. I've tried with two-way binding, but I think, that I make something wrong. Minimal example:

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

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

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


//../pages/_layout.svelte

<Meta bind:title={$_('title.companyTitle')} />  //doesn't work

<Navigation items={items}/>

<div>
    <slot/>
</div>

<Footer contact={contact}/>

//../pages/company.svelte
<LeadSection classes="lg:flex-row-reverse -mt-24">
    <div slot="header">
        { $_('pages.company.header') }
    </div>
...
</LeadSection>

Any ideas how to make this?

Upvotes: 2

Views: 2946

Answers (2)

Waseem
Waseem

Reputation: 1

If you are using routing "svelte-routing" then you must have created the separate pages e.g "Home.svelte", "About.svelte".

On each page add this;

<svelte:head>
    <title> Title here as a plain text </title>
</svelte:head>

You can use a variable if you already have pageName;

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

<script>
    let pageName="Home"; 
</script>

Upvotes: 0

Nathan Herrmann
Nathan Herrmann

Reputation: 46

My understanding is: you want to dynamically set the title. To achieve this you don't have to use two way binding. Two way binding is meant to write back to a variable in the parent component. The "variable" you are trying to bind to is not a variable but a store which can't be used for binding. Just pass the title in as a normal prop and it should work:

//../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" />

...

Upvotes: 3

Related Questions