我解决了这一问题,不试图与路上的所有东西相匹配,在装载部件中处理其中一部分。
因此,有<代码>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}