Reputation: 31
For example, I have a component blog-post.svelte. This component contains the basic layout for my blog post. Then based on data of fetch endpoints, I want to create different pages from component blog-post.svelte.
Upvotes: 2
Views: 1638
Reputation: 328
If you're not interested in diving into Sapper and SSR, it's not too difficult to implement your own simple hash routing on the client side, utilising the <svelte:component>
special element, to achieve what you're after.
Here's a small project I threw together to show how you might go about it: https://github.com/joshmanderson/svelte-blog-hash-router-example
And here's a demo: https://svelte-blog-hash-router-example-437uuzkc5.now.sh
One caveat with that solution is that all the blog post hashes are of the form: post-{id}
to be able to easily match the blog post route. There are ways around that of course, for example: if the current hash doesn't match any predefined routes you could assume that it's a blog post, then if you can't find a matching blog post you can fall back to your not found or index route. However you would want to implement that is totally up to you though.
Upvotes: 0
Reputation: 4072
You can instantiate components dynamically with <svelte:component>
, so you could potentially pick different components based on your current endpoint :
<script>
// Import all your components here
let myComponent = false;
let endpoint = ; // add your code to determine your endpoint here
switch (endpoint) {
case 'endpoint 1':
myComponent = EndpointComponent1;
break;
case 'endpoint 2':
myComponent = EndpointComponent2;
break;
case 'endpoint 3':
myComponent = EndpointComponent3;
break;
default:
myComponent = DefaultEndpointComponent;
break;
}
</script>
<svelte:component this={myComponent} />
Upvotes: 1