Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.4k 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 Reply

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>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...