English 中文(简体)
我怎样才能在SvelteKit路线的配对器上接上以前的路线?
原标题:How can I get previous route matches in a SvelteKit route matcher?
  • 时间:2023-12-08 14:07:50
  •  标签:
  • sveltekit

I m trying to set up my site for internationalized urls so I can match on urls like /en/privacy and /es/privacidad. But a url like /en/privacidad should be a 404

我建立了像双管齐下的结构。

routes
  [lang=lang]
    [route1=route1]

But I can t figure out how to get the current language in the route1 route matcher.

把它从纸库中提出去是没有工作的,因为它是外部的组成部分。 我也不知道如何从线路配对机从服务器和客户手中接手以来获得全程。

我如何在一条路线上与以前的道路相匹配或全程相匹配?

最佳回答

我解决了这一问题,不试图与路上的所有东西相匹配,在装载部件中处理其中一部分。

因此,有<代码>urls.json文档,以界定每一可能的路线1:


{
  "en": {
    "route1": {
      "privacy": "privacy",
      "search": "search"
    }
  },
  "es": {
    "route1": {
      "privacy": "privacidad",
      "search": "buscar"
    }
  }
}

In the params/route1.ts then make sure the route matches any of the languages:

import type { ParamMatcher } from "@sveltejs/kit"
import urls from  $lib/urls.json ;
import { findMatchingValues } from "$lib/findMatchingValues";

export const match = (function match(param) {
  const matches = findMatchingValues<string>(urls, "*.route1.*");
  return matches.includes(param);
}) satisfies ParamMatcher;

在<代码>routes/[lang=lang]/[route1=route1]/+page.ts文档中,发现哪些网页与数据相匹配并交:

import type { PageLoad } from  ./$types 
import urls from  $lib/urls.json ;
import type { LocaleCode } from  $lib/poly-i18n/locales ;
import { error } from  @sveltejs/kit ;

export const load: PageLoad = async ({ params, parent, data }) => {
  const lang = params.lang as LocaleCode;
  const route1 = params.route1.toLowerCase();
  const { t } = await parent();

  const route1Urls: Record<string, string> = urls[lang].route1;
  const matched = Object.keys(route1Urls).find(key => route1Urls[key] === route1);

  if (!matched) {
    throw error(404,  Page +   + t( common.notFound , { values: { route: route1 ??    } }));
  }

  return {
    matched,
    ...data
  }
}

最终载于routes/[lang=lang]/[route1=route1]/+page.svelte。 积极使配对部分成为配对部分

<script lang="ts">
    import Privacy from  $pages/privacy/+page.svelte ;
    import Search from  $pages/search/+page.svelte ;
    import { browser } from  $app/environment ;
    import { goto } from  $app/navigation ;

    export let data;

    let matched: string;
    let component: ConstructorOfATypedSvelteComponent | undefined = undefined;

    $: {
        matched = data.matched;

        switch (matched) {
            case  search :
                component = Search;
                break;
            case  privacy :
                component = Privacy;
                break;
        }

        if (!component) {
            if (browser) {
                goto(`/${data.lang}/`);
            }
        }
    }
</script>

{#if component}
    <svelte:component this={component} {data} />
{/if}
问题回答

暂无回答




相关问题
当地储存具有初步价值的Svelte仓库

我试图在我的SvelteKit SPA中实施JWT认证。 I m new to TS (and, Svelte[Kit]),有很多东西可以学习,因此,我的问题可能并非严格地与Svelte及其储存系统......。

热门标签