乐闻世界logo
搜索文章和话题

How to change page title dynamically in Sveltekit?

1个答案

1

In SvelteKit, dynamically modifying page titles is a highly practical feature, especially when building single-page applications (SPAs), as it enhances user experience and SEO optimization. I will explain how to implement this feature in detail, along with code examples.

First, understand how pages are structured in a SvelteKit application. SvelteKit uses the file system for routing, meaning the project's directory structure directly defines the application's routing hierarchy. Each page typically includes a corresponding +page.svelte file, and may also feature a +layout.svelte file for defining the page's layout.

Step 1: Using +page.js or +page.ts Files

To dynamically modify page titles, work within the +page.js or +page.ts files. These files handle page data loading and logic processing. Here, you can update document.title to change the page title.

Example Code:

Assume we have a product details page where we want to dynamically set the page title based on the product name.

src/routes/products/[id]/+page.svelte:

svelte
<script> // Import page logic and data export let product; </script> <h1>{product.name}</h1> <p>{product.description}</p>

src/routes/products/[id]/+page.js:

javascript
export async function load({ fetch, params }) { const res = await fetch(`/api/products/${params.id}`); const product = await res.json(); // Dynamically set page title if (typeof document !== 'undefined') { document.title = `${product.name} - Product Details`; } return { props: { product } }; }

Step 2: Using SvelteKit's Head Management Feature

Starting from SvelteKit v1.0, the framework supports managing HTML head elements directly within Svelte files. This allows you to conveniently handle titles in .svelte files.

Using the <svelte:head> Tag to Set Titles:

svelte
<script> export let product; </script> <svelte:head> <title>{product.name} - Product Details</title> </svelte:head> <h1>{product.name}</h1> <p>{product.description}</p>

Summary

Both methods enable dynamic page title modification in SvelteKit. The first method is ideal for setting titles at page load time, while the second offers a more declarative approach for handling titles and other head elements. The choice depends on specific project requirements and developer preferences.

2024年8月16日 22:00 回复

你的答案