Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

if statement - Is there a better way in Svelte to include a conditional HTML element

I started to come across this problem a lot. I want to include an element around other elements if a boolean is true. In the example below I make two if statements, but if the code that I want to wrap is big this will make it unclear what is happening. Also, there will be duplicate code. Is there a better way to this solution?

<script>
   let boolean = true;
</script>

{#if}
   <img src="source" />
{/if}

{#if}
   <a href="/home">
      <img src="source" />
   </a>
{/if}
question from:https://stackoverflow.com/questions/65835464/is-there-a-better-way-in-svelte-to-include-a-conditional-html-element

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

If this is something you find yourself doing often, you could make a ConditionalLink component out of it using slots.

<!-- ConditionalLink.svelte -->
<script>
    export let isWrapped = false;
    export let href;
</script>

{#if isWrapped}
<a {href}>
    <slot/>
</a>
{:else}
<slot/>
{/if}

It can be used like so:

<script>
    import ConditionalLink from './ConditionalLink.svelte'; 
    let wrapLink = false;
</script>

<ConditionalLink isWrapped={wrapLink} href="#">
    I'm a link
</ConditionalLink>

<label><input type="checkbox" bind:checked={wrapLink}> wrap link</label>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...