Autor:
    Data utworzenia:2026-06-22Ostatnia aktualizacja:2026-06-22

    Integracja ze Svelte: Dokumentacja usePathname

    Funkcja usePathname zwraca bieżącą ścieżkę przeglądarki (pathname) z usuniętym segmentem locale jako Readable<string> ze Svelte. Jest to przydatne do budowania nawigacji uwzględniającej locale — na przykład określania, który element nawigacji jest aktywny — bez konieczności ręcznego usuwania prefiksu locale.

    Importowanie usePathname w Svelte

    typescript
    import { usePathname } from "svelte-intlayer";

    Przegląd

    usePathname tworzy store w Svelte w trybie tylko do odczytu (readable store), który odczytuje window.location.pathname, usuwa prefiks locale za pomocą getPathWithoutLocale i emituje nową wartość za każdym razem, gdy przeglądarka wywoła zdarzenie popstate (nawigacja wstecz/dalej). Subskrybuj przy użyciu składni $ w komponentach.

    Użycie

    src/components/NavItem.svelte
    <script lang="ts">  import { usePathname } from "svelte-intlayer";  export let href: string;  export let label: string;  const pathname = usePathname();</script><a {href} aria-current={$pathname === href ? "page" : undefined}>  {label}</a>

    Zwracana wartość

    Typ Opis
    Readable<string> Readable store ze Svelte, zawierający bieżącą ścieżkę (pathname) bez prefiksu locale.

    Zachowanie

    • Usuwanie locale: Usuwa początkowy segment locale (np. /pl/dashboard/dashboard).
    • Reaktywność: Emituje nową wartość po każdym zdarzeniu popstate (nawigacja w przeglądarce w tył/w przód).
    • Bezpieczeństwo w SSR: Zwraca "", gdy obiekt window nie jest dostępny.
    • Czyszczenie (Cleanup): Nasłuchiwacz popstate jest automatycznie usuwany po odsubskrybowaniu ostatniego subskrybenta.

    Przykład

    src/components/Sidebar.svelte
    <script lang="ts">  import { usePathname } from "svelte-intlayer";  const links = [    { href: "/dashboard", label: "Panel sterowania" },    { href: "/settings", label: "Ustawienia" },  ];  const pathname = usePathname();</script><nav>  {#each links as link}    <a      href={link.href}      style:font-weight={$pathname === link.href ? "bold" : "normal"}    >      {link.label}    </a>  {/each}</nav>

    Zobacz również