Description
Describe the problem
React.js defines components with function components and it has some great benefits. For example you can use return keyword to return a template based on a condition and be sure that nothing else will be rendered:
export default function Gallery {
if (loading) return (<p>Loading...</p>)
return // ..........
}
but in Svelte we have to do this with if-else blocks. And you know a redundant else block and may be redundant indentation. Another thing that React has and Svelte don't is That you can put template parts to a variable even a function and then re-use it easily. I know that you can create components for that but in most cases creating component is just too much work.
Here is a code example in one of my projects:
<Button
color={CssColors.purple.withAlpha(0.2).s()}
hoverColor={CssColors.purple.withAlpha(0.5).s()}
borderColor={CssColors.purple.withAlpha(0.5).s()}
textColor={CssColors.black.withAlpha(0.7).s()}
>
<Fa icon={faPlus} color="crimson" />
<p>Note</p>
</Button>
<Button
color={CssColors.purple.withAlpha(0.2).s()}
hoverColor={CssColors.purple.withAlpha(0.5).s()}
borderColor={CssColors.purple.withAlpha(0.5).s()}
textColor={CssColors.black.withAlpha(0.7).s()}
>
<Fa icon={faMinus} color="purple" />
<span>Note</span>
</Button>
The only difference between these two buttons are the faPlus
and faMinus
. I would like to be able to make this code a little more concise.
Describe the proposed solution
For the first feature (the return keyword scenario) I can't come up with a decent solution.
For the second though there are multiple ways. But let me first point out that template is just a string and no matter where we declare it, right? (correct me if I'm wrone)
So my proposed solution is that we let the programmer define a template with template keyword that accepts a function (0 to inf arguments) in the script tag of the .svelte file and use it inside the template. So my problem can be solved (kinda) with following code :
<script>
template noteButton = (icon) => (
<Button
color={CssColors.purple.withAlpha(0.2).s()}
hoverColor={CssColors.purple.withAlpha(0.5).s()}
borderColor={CssColors.purple.withAlpha(0.5).s()}
textColor={CssColors.black.withAlpha(0.7).s()}
>
<Fa icon={icon} color="crimson" />
<p>Note</p>
</Button>
)
</script>
noteButton(faPlus)
noteButton(faMinus)
Alternatives considered
I know there are multiple ways to do this. Since svelte is a compiler. It would be great to have some features that other frameworks have.
Importance
would make my life easier