Conditional parent #11486
-
Hi, Let's take this piece of code for example... const data = [
{wrapper: true, content:'test1'},
{wrapper: false, content:'test2'}
] {#each data as (wrapper, content)}
<div class="wrapper">
<div class="content">{content}</div>
</div>
{/each} Is there a way to conditionally render the 'wrapper' (parent) div based on the wrapper boolean value, but always render the inner 'content' div? |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
In Svelte 5 you can use a snippet: {#each data as { wrapper, content }}
{#snippet contentSnippet()}
<div class="content">{content}</div>
{/snippet}
{#if wrapper}
<div class="wrapper">{@render contentSnippet()}</div>
{:else}
{@render contentSnippet()}
{/if}
{/each} In Svelte 4, you probably have to either duplicate the content or extract it to a separate component. You can also implement a generic conditional wrapper component. <ConditionalWrapper condition={wrapper}>
<div class="content">{content}</div>
</ConditionalWrapper> <!-- ConditionalWrapper.svelte -->
<script>
export let condition;
export let tagName = 'div';
</script>
{#if condition}
<svelte:element this={tagName} {...$$restProps}>
<slot />
</svelte:element>
{:else}
<slot />
{/if} Styling will be less nice, though, since the scoping prevents targeting the element unless If you just don't want the element affecting layout, you could also conditionally apply classes and set {#each data as { wrapper, content }}
<div class:wrapper class:contents={!wrapper}>
<div class="content">{content}</div>
</div>
{/each} |
Beta Was this translation helpful? Give feedback.
In Svelte 5 you can use a snippet:
REPL
In Svelte 4, you probably have to either duplicate the content or extract it to a separate component.
You can also implement a generic conditional wrapper component.