Access current page name from __layout.svelte

Viewed 259

I have a bunch of routes in a directory, with a common __layout.svelte file, let's say a following structure:

- src
  - routes
    - common
      - __layout.svelte
      - page_a.svelte
      - page_b.svelte

I'd like to know in __layout.svelte the name of the page I'm currently in. E.g. when I'm on /common/page_a I want __layout to display page_a. This would be easy if I'd have dynamic routing and a file [name].svelte, then I could access name value by page.params.name, but since these are static I don't know how to access it reliably in another way than parsing the URL.

1 Answers

sveltekit provides a store named page, you can import it as import {page} from '$app/stores since it's a store you can access the value like this $page.url.pathname and it will be reactive, if you only want the last part of the url you can use some string methods to extract it for this specific one something like this would work $page.url.pathname.substr($page.url.pathname.lastIndexOf('/'))

Related