Svelte Template

{#if...}

2025-06-10

{#if...} 是 [[Svelte]] 中的条件语句,可以实现条件渲染。

语法

{#if expression}...{/if}
{#if expression}...{:else}...{/if}
{#if expression}...{:else if expression}...{/if}

所有条件都是由 {#if} 开启,{/if} 关闭;{:else}{:else if} 都是用冒号 : 前缀。

使用

if

{#if count > 10 }
<p>{count} is greater than 10</p>
{/if}

if..else

{#if count > 10}
<p>{count} is greater than 10</p>
{:else}
<p>{count} is between 0 and 10</p>
{/if}

else if

{#if count > 10}
<p>{count} is greater than 10</p>
{:else if count < 5}
<p>{count} is less than 5</p>
{:else}
<p>{count} is between 0 and 10</p>
{/if}