逻辑树模板
Any good templating language for the Web provides you at least 2 things: a conditional structure, and a loop.
Web上任何好的模板语言都至少为您提供两点:条件结构和循环。
Svelte is no exception, and in this post I’ll look into conditional structures.
Svelte也不例外,在这篇文章中,我将研究条件结构。
You want to be able to look at a value/expression, and if that points to a true value do something, if that points to a false value then do something else.
您希望能够查看一个值/表达式,如果该值/值指向一个真值,则执行某些操作,如果该值/值指向一个假值,则执行其他操作。
Svelte provides us a very powerful set of control structures.
Svelte为我们提供了非常强大的控制结构集。
The first is if:
第一个是,如果 :
{#if isRed}
<p>Red</p>
{/if}
There is an opening {#if}
and an ending {/if}
. The opening markup checks for a value or statement to be truthy. In this case isRed
can be a boolean with a true
value:
有一个开头{#if}
和一个结尾{/if}
。 开头标记检查值或语句是否真实。 在这种情况下, isRed
可以是具有true
值的布尔值:
<script>
let isRed = true
</script>
An empty string is falsy, but a string with some content is truthy.
空字符串是虚假的,但包含某些内容的字符串是虚假的。
0 is falsy, but a number > 0 is truthy.
0是虚假的,但数字> 0是真实的。
The boolean value true
is truthy, of course, and false
is falsy.
布尔值true
当然是真实的,而false
是虚假的。
If the opening markup is not satisfied (a falsy value is provided), then nothing happens.
如果不满足打开标记(提供虚假值),则什么都不会发生。
To do something else if that’s not satisfied, we use the appropriately called else
statement:
如果不满意,可以做其他事情,我们使用适当地调用else
语句:
{#if isRed}
<p>Red</p>
{:else}
<p>Not red</p>
{/if}
Either the first block is rendered in the template, or the second one. There’s no other option.
第一个块将在模板中呈现,或者第二个块将在模板中呈现。 没有其他选择。
You can use any JavaScript expression into the if
block condition, so you can negate an option using the !
operator:
您可以在if
块条件中使用任何JavaScript表达式,因此可以使用!
取反选项!
操作员:
{#if !isRed}
<p>Not red</p>
{:else}
<p>Red</p>
{/if}
Now, inside the else
you might want to check for an additional condition. That’s where the {:else if somethingElse}
syntax comes along:
现在,在else
内部,您可能想要检查其他条件。 这就是{:else if somethingElse}
语法的来源:
{#if isRed}
<p>Red</p>
{:else if isGreen}
<p>Green</p>
{:else}
<p>Not red nor green</p>
{/if}
You can have many of these blocks, not just one, and you can nest them. Here’s a more complex example:
您可以有许多这样的块,而不仅仅是一个,并且可以嵌套它们。 这是一个更复杂的示例:
{#if isRed}
<p>Red</p>
{:else if isGreen}
<p>Green</p>
{:else if isBlue}
<p>It is blue</p>
{:else}
{#if isDog}
<p>It is a dog</p>
{/if}
{/if}
逻辑树模板