I'm iterating over an array of data and I want to do some processing on it before rendering it.
I know that I could create a new component and pass array entry to i, and do the processing within that sub-component, or I could add a helper function getClass(entry)
or I could inline a tenary operator,
but I'm wondering if there's a way to do something like this, to inline some code into the each block. Non-functional example:
<div class="Menu">
{#each menuEntries as entry, i }
{{
let classes = entry.classes;
if (entry.submenu) {
classes += ' has-submenu';
}
}}
<div class="menu-entry {classes}">...</div>
{/each}
</div>
Edit:
It seems like a workaround like this works. The only thing is that classes
have to be defined before the loop.
<script>
let classes = '';
</script>
<div class="Menu">
{#each menuEntries as entry, i }
{(() => {
classes = entry.classes;
if (entry.submenu) {
classes += ' has-submenu';
}
return ''; // return empty string so Svelte does not print it
})()}
<div class="menu-entry {classes}">...</div>
{/each}
</div>