Improved optional route link generation #10017
alexvdvalk
started this conversation in
Ideas
Replies: 1 comment
-
This component solved the issue for me. <script lang="ts">
import { page } from "$app/stores";
export let routeKey: string;
export let value: string;
const optionalRegex = /\[\[.*\]\]/;
$: validKey = $page.route.id?.includes(`[[${routeKey}]]`);
let link = "";
$: {
link = $page.route.id!.replace(`[[${routeKey}]]`, value);
for (let key in $page.params) {
link = link.replace(`[[${key}]]`, $page.params[key] || ""); // If optional route exists, replace it with the existing value
link = link.replace(`[${key}]`, $page.params[key]); // Required routes will always exist
}
link = link.replace(optionalRegex, ""); // remove any optional route paths that are not currently used.
}
</script>
{#if !validKey}
<p>Invalid key provided</p>
{:else}
<slot {link} />
{/if} |
Beta Was this translation helpful? Give feedback.
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
-
I have a route like this: /[[lang]]/products/[[id]]
In my layout, I have a language picker, but I have to add some complex logic to determine what the href attribute should be based on where the user is. This includes checking if there is an existing params.lang and params.id, and then building out the correct href. This can much more complex as I add additional routes.
It would be great if there was a utility function where i pass it a value and route key ('lang') and it gives me back the current url with the optional [[lang]] param either added or updated to reflect my passed value.
There may be a simple solution here but my brain is not able to work it out right now.
Beta Was this translation helpful? Give feedback.
All reactions