svelte

Can you add optional _outer_ tags in svelte conditional statement?


Is it possible to use a conditional statement to wrap inner content with an optional outer element?

Here is an example of what I want to do in valid Svelte:

<script>
  export let needs_div_wrapper;
</script>

{#if needs_div_wrapper}
  <div>
    <a>My static content!</a>
  </div>
{:else}
  <a>My static content!</a>
{/if}

And here is an example in non-valid Svelte that demonstrates what I want to do:

...

{#if needs_div_wrapper}
  <div>
{/if}
    <a>My static content!</a>
{#if needs_div_wrapper}
  </div>
{/if}

EDIT: Just for clarity, I'm trying to accomplish this without a new component for the inner content.


Solution

  • No, it is not possible.

    A wrapper component is probably the cleanest you can do in this case, to avoid repeating potentially non trivial markup in the "parent" component.

    As I understand it, you've already found this solution, but for the record here's what I mean:

    DivWrapper.svelte

    <script>
      export let wrap = false
    </script>
    {#if wrap}
      <div {...$$restProps}>
        <slot />
      </div>
    {:else}
      <slot />
    {/if}
    

    App.svelte

    <script>
      import DivWrapper from './DivWrapper.svelte'
    
      export let needs_div_wrapper;
    </script>
    
    <DivWrapper wrap={needs_div_wrapper}>
      <a>My static content!</a>
    </DivWrapper>