I have looked at the documentation for [<svelte:component>]
(here), but that looks like I would have had to import
all of the possible templates at compile time.
Is it possible in Svelte to load any number of arbitrary templates from something like a fetch()
call based on a user action? Then inject data into it?
Would it be inefficient to use <slot>
for something like this, if I plan on updating it after the initial load?
<svelte:component> is a special Svelte element that allows you to accomplish the dynamic rendering. You pass the component you want to render as the value for a prop called this to the special element, in addition to any other props you want the child component to have.
Svelte will generate the code to automatically update them whenever data they depend on is changed. Note: Svelte uses the $: JavaScript label statement syntax to mark reactive statements.
3. $: marks a statement as reactive. Any top-level statement (i.e. not inside a block or a function) can be made reactive by prefixing it with the $: JS label syntax. Reactive statements run after other script code and before the component markup is rendered, whenever the values that they depend on have changed.
Svelte was designed to compile the template at build time. I'd recommend using a template engine (like handlebars) for your use case. This of course limits the available syntax to handlebars, and you can't use svelte components inside a handlebar template.
It's technically possible to create a component from the source text — the REPL does it, for example — since the compiler doesn't care if it's running in Node or the browser. But it's definitely not recommended! (It would defeat the object of using Svelte, since the compiler is somewhat large.)
Instead, you can dynamically import the components themselves, if you're using Rollup (with experimentalDynamicImport
and experimentalCodeSplitting
) or webpack:
<button on:click="loadChatbox()">
chat to a customer service representative
</button>
{#if ChatBox}
<svelte:component this={ChatBox}/>
{/if}
<script>
export default {
methods: {
async loadChatbox() {
const { default: Chatbox } = await import('./Chatbox.html');
this.set({ Chatbox });
}
}
};
</script>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With