Reusable HTML snippets (or svelte's answer for React's arrow function components)
See original GitHub issueIs your feature request related to a problem? Please describe. Yes! I’m frustrated that we can’t reuse simple html code within a single component file, to use internally by this component alone (i.e. “arrow function components” in React)…
consider the following component:
<script>
let id, src, ... // more props
</script>
{#if id === 'x'}
<h1>I am X</h1>
<div>
<img src={src} .../>
</div>
{:else if id === 'y'}
<h2>I am Y</h2>
<div>
<img src={src} .../>
</div>
{:else if id === 'z'}
<h3>I am Z</h3>
<div>
<img src={src} .../>
</div>
{:else}
<pre>not supported</pre>
{/if}
Since the <div><img .../></div>
snippet is reused, my code is now bloated with boilerplate 😞 .
Describe the solution you’d like
<script>
let id, src, ... // more props
</script>
<script type="scopedComponent">
const MyImg = `
<div>
<img src=${src} .../>
</div>
`
</script>
{#if id === 'x'}
<h1>I am X</h1>
<MyImg />
{:else if id === 'y'}
<h2>I am Y</h2>
<MyImg />
{:else if id === 'z'}
<h3>I am Z</h3>
<MyImg />
{:else}
<pre>not supported</pre>
{/if}
- the
type="scopedComponent"
and string template is just a made-up API, don’t take it as a suggestion… - notice that the scoped component can access the props directly, that is also necessary.
Describe alternatives you’ve considered
Writing an additional .svelte
for the above, But it has its own cost. For example, the reused html requires many props, I need the root component passing them again and again which bloats my code again…
How important is this feature to you? My team develop a huge-scale and mission critical app based on svelte. Without a simple and elegant solution for reusing code within the same component we’re gonna have tons of redundant code.
Issue Analytics
- State:
- Created 4 years ago
- Reactions:1
- Comments:10 (4 by maintainers)
I ended up hacking up something when I needed to do this. (not advised) https://svelte.dev/repl/4531f96e7f8a4d40adfdfd3a4f379893?version=3.12.1
then use like
This feature is going to be implemented with this RFC: https://github.com/sveltejs/rfcs/pull/34